File: gsm_phonebook.cc

package info (click to toggle)
gsmlib 1.10+20120414.gita5e5ae9a-0.3
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 3,468 kB
  • ctags: 1,907
  • sloc: cpp: 12,315; sh: 11,376; ansic: 2,366; makefile: 263; sed: 93
file content (584 lines) | stat: -rw-r--r-- 16,030 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
// *************************************************************************
// * GSM TA/ME library
// *
// * File:    gsm_phonebook.cc
// *
// * Purpose: Phonebook management functions
// *
// * Author:  Peter Hofmann (software@pxh.de)
// *
// * Created: 6.5.1999
// *************************************************************************

#ifdef HAVE_CONFIG_H
#include <gsm_config.h>
#endif
#include <gsmlib/gsm_nls.h>
#include <gsmlib/gsm_sysdep.h>
#include <gsmlib/gsm_phonebook.h>
#include <gsmlib/gsm_parser.h>
#include <gsmlib/gsm_me_ta.h>
#include <sstream>
#include <iostream>
#include <assert.h>
#include <ctype.h>

using namespace gsmlib;

// PhonebookEntry members

PhonebookEntry::PhonebookEntry(const PhonebookEntryBase &e)
  throw(GsmException) : _cached(true), _myPhonebook(NULL)
{
  set(e.telephone(), e.text(), e.index(), e.useIndex());
}

void PhonebookEntry::set(std::string telephone, std::string text, int index,
                         bool useIndex)
  throw(GsmException)
{
  checkTextAndTelephone(text, telephone);

  if (_myPhonebook != NULL)
  {
    if (text.length() > _myPhonebook->getMaxTextLen())
      throw GsmException(
        stringPrintf(_("length of text '%s' exceeds maximum text "
                       "length (%d characters) of phonebook '%s'"),
                     text.c_str(), _myPhonebook->getMaxTextLen(),
                     _myPhonebook->name().c_str()),
        ParameterError);
    
    if (telephone.length() > _myPhonebook->getMaxTelephoneLen())
      throw GsmException(
        stringPrintf(_("length of telephone number '%s' " 
                       "exceeds maximum telephone number "
                       "length (%d characters) of phonebook '%s'"),
                     telephone.c_str(), _myPhonebook->getMaxTelephoneLen(),
                     _myPhonebook->name().c_str()),
        ParameterError);

    _myPhonebook->writeEntry(_index, telephone, text);
  }
  else
    _index = index;

  _useIndex = useIndex;
  _cached = true;
  _telephone = telephone;
  _text = text;
  _changed = true;
}

std::string PhonebookEntry::text() const throw(GsmException)
{
  if (! cached())
  {
    assert(_myPhonebook != NULL);
    // these operations are at least "logically const"
    PhonebookEntry *thisEntry = const_cast<PhonebookEntry*>(this);
    _myPhonebook->readEntry(_index, thisEntry->_telephone, thisEntry->_text);
    thisEntry->_cached = true;
  }
  return _text;
}

std::string PhonebookEntry::telephone() const throw(GsmException)
{
  if (! cached())
  {
    assert(_myPhonebook != NULL);
    // these operations are at least "logically const"
    PhonebookEntry *thisEntry = const_cast<PhonebookEntry*>(this);
    _myPhonebook->readEntry(_index, thisEntry->_telephone, thisEntry->_text);
    thisEntry->_cached = true;
  }
  return _telephone;
}

bool PhonebookEntry::cached() const
{
  if (_myPhonebook == NULL)
    return _cached;
  else
    return _cached && _myPhonebook->_useCache;
}

PhonebookEntry::PhonebookEntry(const PhonebookEntry &e) throw(GsmException)
{
  set(e._telephone, e._text, e._index, e._useIndex);
}

PhonebookEntry &PhonebookEntry::operator=(const PhonebookEntry &e)
  throw(GsmException)
{
  set(e._telephone, e._text, e._index, e._useIndex);
  return *this;
}

// Phonebook members

int Phonebook::parsePhonebookEntry(std::string response,
                                   std::string &telephone, std::string &text)
{
  // this is a workaround for a bug that occurs with my ME/TA combination
  // some texts are truncated and don't have a trailing "
  if (response.length() > 0 && response[response.length() - 1] != '"')
    response += '"';
  Parser p(response);

  int index = p.parseInt();
  p.parseComma();

  // handle case of empty entry
  if (p.getEol().substr(0, 5) == "EMPTY")
  {
    telephone = "";
    text = "";
    return index;
  }

  telephone = p.parseString();
  p.parseComma();
  unsigned int numberFormat = p.parseInt();
  if (numberFormat != UnknownNumberFormat &&
      numberFormat != InternationalNumberFormat)
    std::cerr << "*** GSMLIB WARNING: Unexpected number format when reading from "
	      << "phonebook: " << numberFormat << " ***" << std::endl;
  p.parseComma();
  text = p.parseString(false, true);
  if (lowercase(_myMeTa.getCurrentCharSet()) == "gsm")
    text = gsmToLatin1(text);
  if (numberFormat == InternationalNumberFormat)
  {
    // skip leading "+" signs that may already exist
    while (telephone.length() > 0 && telephone[0] == '+')
      telephone = telephone.substr(1);
    telephone = "+" + telephone;
  }

  return index;
}

void Phonebook::readEntry(int index, std::string &telephone, std::string &text)
  throw(GsmException)
{
  // select phonebook
  _myMeTa.setPhonebook(_phonebookName);

  // read entry
  std::string response = _at->chat("+CPBR=" + intToStr(index), "+CPBR:",
                              false, // dont't ignore errors
                              true); // but accept empty responses
  // (the latter is necessary for some mobile phones that return nothing
  // if the entry is empty)

  if (response.length() == 0)   // OK phone returned empty response
  {
    telephone = text = "";      // then the entry is empty as well
  }
  else
    parsePhonebookEntry(response, telephone, text);

#ifndef NDEBUG
  if (debugLevel() >= 1)
    std::cerr << "*** Reading PB entry " << index << " number " << telephone 
	      << " text " << text << std::endl;
#endif
}

void Phonebook::findEntry(std::string text, int &index, std::string &telephone)
  throw(GsmException)
{
  // select phonebook
  _myMeTa.setPhonebook(_phonebookName);

  // read entry
  std::string response = _at->chat("+CPBF=\"" + text + "\"", "+CPBF:",
                              false, // dont't ignore errors
                              true); // but accept empty responses
  // (the latter is necessary for some mobile phones that return nothing
  // if the entry is empty)

  if (response.length() == 0)   // OK phone returned empty response
  {
    telephone = "";      // then the entry is empty as well
    index = 0;
  }
  else
    index=parsePhonebookEntry(response, telephone, text);

#ifndef NDEBUG
  if (debugLevel() >= 1)
    std::cerr << "*** Finding PB entry " << text << " number " << telephone 
	      << " index " << index << std::endl;
#endif
}

void Phonebook::writeEntry(int index, std::string telephone, std::string text)
  throw(GsmException)
{
#ifndef NDEBUG
  if (debugLevel() >= 1)
    std::cerr << "*** Writing PB entry #" << index << " number '" << telephone
	      << "' text '" << text << "'" << std::endl;
#endif
  // select phonebook
  _myMeTa.setPhonebook(_phonebookName);

  // write entry
  std::string s;
  if (telephone == "" && text == "")
  {
    std::ostringstream os;
    os << "+CPBW=" << index;
    os << std::ends;
    s = os.str();
  }
  else
  {
    int type;
    if (telephone.find('+') == std::string::npos)
      type = UnknownNumberFormat;
    else
      type = InternationalNumberFormat;
    std::string gsmText = text;
    if (lowercase(_myMeTa.getCurrentCharSet()) == "gsm")
      gsmText = latin1ToGsm(gsmText);
    std::ostringstream os;
    os << "+CPBW=" << index << ",\"" << telephone << "\"," << type
       << ",\"";
    os << std::ends;
    s = os.str();
    // this cannot be added with ostrstream because the gsmText can
    // contain a zero (GSM default alphabet for '@')
    s += gsmText + "\"";
  }
  _at->chat(s);
}

Phonebook::iterator Phonebook::insertFirstEmpty(std::string telephone, std::string text)
  throw(GsmException)
{
  for (int i = 0; i < _maxSize; i++)
    if (_phonebook[i].empty())
    {
      _phonebook[i].set(telephone, text);
      adjustSize(1);
      return begin() + i;
    }
  throw GsmException(_("phonebook full"), OtherError);
}

Phonebook::iterator Phonebook::insert(const std::string telephone,
                                      const std::string text,
                                      const int index)
{
  for (int i = 0; i < _maxSize; i++)
    if (_phonebook[i].index() == index)
      {
	if (_phonebook[i].empty())
	  {
	    _phonebook[i].set(telephone, text);
	    adjustSize(1);
	    return begin() + i;
	  }
	else
	  throw GsmException(_("attempt to overwrite phonebook entry"),
			     OtherError);
      }
  return end();
}

Phonebook::Phonebook(std::string phonebookName, Ref<GsmAt> at, MeTa &myMeTa,
                     bool preload) throw(GsmException) :
  _phonebookName(phonebookName), _at(at), _myMeTa(myMeTa), _useCache(true)
{
  // select phonebook
  _myMeTa.setPhonebook(_phonebookName);

  // query size and maximum capacity of phonebook
  _size = -1;                   // -1 means not known yet
  _maxSize = -1;
  Parser q(_at->chat("+CPBS?", "+CPBS:"));
  std::string dummy = q.parseString();
  if (q.parseComma(true))       // this means that
  {                             // used and total result is supported by ME
    _size = q.parseInt();
    q.parseComma();
    _maxSize = q.parseInt();
  }
  
  // get basic phonebook info from ME
  Parser p(_at->chat("+CPBR=?", "+CPBR:"));

  // get index of actually available entries in the phonebook
  std::vector<bool> availablePositions = p.parseIntList();
  p.parseComma();
  _maxNumberLength = p.parseInt();
  p.parseComma();
  _maxTextLength = p.parseInt();
  
  // find out capacity of phonebook in ME
  // Note: The phonebook in the ME may be sparse, eg. the range of
  // allowed index numbers may be something like (3-4, 20-100, 120).
  // The standard allows this, even though it is unlikely to be 
  // implemented like that by anyone.
  // In memory we store only phonebook entries that may actually be
  // used, ie. the phonebook in memory is not sparse.
  // Each entry has a member _index that corresponds to the index in the ME.
  if (_maxSize == -1)
  {
    _maxSize = 0;
    for (std::vector<bool>::iterator i = availablePositions.begin();
         i != availablePositions.end(); ++i)
      if (*i) ++_maxSize;
  }

  // for use with preload below
  int *meToPhonebookIndexMap =
    (int*)alloca(sizeof(int) * (availablePositions.size() + 1));

  // initialize phone book entries
  if (_maxSize == 0)
    _phonebook = NULL;
  else
    _phonebook = new PhonebookEntry[_maxSize];
  int nextAvailableIndex = 0;
  int i;
  for (i = 0; i < _maxSize; i++)
  {
    while (! availablePositions[nextAvailableIndex])
      nextAvailableIndex++;
    _phonebook[i]._index = nextAvailableIndex;
    _phonebook[i]._cached = false;
    _phonebook[i]._myPhonebook = this;
    meToPhonebookIndexMap[nextAvailableIndex++] = i;
  }

  // find out first index number of phonebook
  int firstIndex = -1;
  for (i = 0; i < _maxSize; i++)
    if (availablePositions[i])
    {
      firstIndex = i;
      break;
    }

  // preload phonebook
  // Note: this contains a workaround for the bug that
  // some MEs can not return the entire phonebook with one AT command
  // To detect this condition, _size must be known
  // also, this code only handles non-sparse phonebooks
  if (preload && _size != -1 && 
      (int)availablePositions.size() == _maxSize + firstIndex)
  {
    int entriesRead = 0;
    int startIndex = firstIndex;

    while (entriesRead < _size)
    {
      reportProgress(0, _maxSize); // chatv also calls reportProgress()
      std::vector<std::string> responses =
        _at->chatv("+CPBR=" + intToStr(startIndex) +
                   "," + intToStr(_maxSize + firstIndex - 1),
                   "+CPBR:", true);

      // this means that we have read nothing even though not all
      // entries have been retrieved (entriesRead < _size)
      // this could be due to a malfunction of the ME...
      // anyway, missing entries can be read later by readEntry()
      if (responses.size() == 0)
      {
#ifndef NDEBUG
        if (debugLevel() >= 1)
	  std::cerr << "*** error when preloading phonebook: "
		    << "not all entries returned" << std::endl;
#endif
        break;
      }

      for (std::vector<std::string>::iterator i = responses.begin();
           i != responses.end(); ++i)
      {
	std::string telephone, text;
        int meIndex = parsePhonebookEntry(*i, telephone, text);
        _phonebook[meToPhonebookIndexMap[meIndex]]._cached = true;
        _phonebook[meToPhonebookIndexMap[meIndex]]._telephone = telephone;
        _phonebook[meToPhonebookIndexMap[meIndex]]._text = text;
        assert(_phonebook[meToPhonebookIndexMap[meIndex]]._index == meIndex);

        ++entriesRead;
        startIndex = meIndex + 1;
#ifndef NDEBUG
        if (debugLevel() >= 1)
	  std::cerr << "*** Preloading PB entry " << meIndex
		    << " number " << telephone 
		    << " text " << text << std::endl;
#endif
      }
    }
  }
}

Phonebook::iterator Phonebook::begin()
{
  return &_phonebook[0];
}

Phonebook::const_iterator Phonebook::begin() const
{
  return &_phonebook[0];
}

Phonebook::iterator Phonebook::end()
{
  return &_phonebook[_maxSize];
}

Phonebook::const_iterator Phonebook::end() const
{
  return &_phonebook[_maxSize];
}

Phonebook::reference Phonebook::operator[](int n)
{
  return _phonebook[n];
}

Phonebook::const_reference Phonebook::operator[](int n) const
{
  return _phonebook[n];
}

Phonebook::reference Phonebook::front()
{
  return _phonebook[0];
}

Phonebook::const_reference Phonebook::front() const
{
  return _phonebook[0];
}

Phonebook::reference Phonebook::back()
{
  return _phonebook[_maxSize - 1];
}

Phonebook::const_reference Phonebook::back() const
{
  return _phonebook[_maxSize - 1];
}

int Phonebook::size() const throw(GsmException)
{
  if (_size != -1)
    return _size;
  else
  {
    int result = 0;
    for (int i = 0; i < _maxSize; i++)
      if (! _phonebook[i].empty())
        result++;
    Phonebook *thisPhonebook = const_cast<Phonebook*>(this);
    thisPhonebook->_size = result;
    return result;
  }
}

Phonebook::iterator Phonebook::insert(iterator position,
                                      const PhonebookEntry& x)
  throw(GsmException)
{
  if (x.useIndex() && x.index() != -1)
    return insert(x.telephone(), x.text(), x.index());
  else
    return insertFirstEmpty(x.telephone(), x.text());
}

void Phonebook::insert (iterator pos, int n, const PhonebookEntry& x)
  throw(GsmException)
{
  for (int i = 0; i < n; i++)
    if (x.useIndex() && x.index() != -1)
      insert(x.telephone(), x.text(), x.index());
    else
      insertFirstEmpty(x.telephone(), x.text());
}

void Phonebook::insert (iterator pos, long n, const PhonebookEntry& x)
  throw(GsmException)
{
  for (long i = 0; i < n; i++)
    if (x.useIndex() && x.index() != -1)
      insert(x.telephone(), x.text(), x.index());
    else
      insertFirstEmpty(x.telephone(), x.text());
}

Phonebook::iterator Phonebook::erase(iterator position)
  throw(GsmException)
{
  if (! position->empty())
  {
    position->set("", "");
    adjustSize(-1);
  }
  return position + 1;
}

Phonebook::iterator Phonebook::erase(iterator first, iterator last)
  throw(GsmException)
{
  iterator i;
  for (i = first; i != last; ++i)
    erase(i);
  return i;
}

void Phonebook::clear() throw(GsmException)
{
  for (iterator i = begin(); i != end(); ++i)
    erase(i);
}

Phonebook::iterator Phonebook::find(std::string text) throw(GsmException)
{
  int index;
  std::string telephone;

  int i;
  for (i = 0; i < _maxSize; i++)
    if (_phonebook[i].text() == text)
      return begin() + i;

  findEntry(text, index, telephone);

  for (i = 0; i < _maxSize; i++)
    if (_phonebook[i].index() == index)
      {
	if (_phonebook[i].cached())
	  {
	    // if entry was already (= cached) and is now different
	    // the SIM card or it's contents were changed
	    if (_phonebook[i]._telephone != telephone ||
		_phonebook[i]._text != text)
	      throw GsmException(_("SIM card changed while accessing phonebook"),
				 OtherError);
	  }
	else
	  {
	    _phonebook[i]._cached = true;
	    _phonebook[i]._telephone = telephone;
	    _phonebook[i]._text = text;
	    return begin() + i;
	  }
      }
  return end();
}

Phonebook::~Phonebook()
{
  delete []_phonebook;
}