From: NeilBrown Date: Mon, 16 Dec 2013 03:53:48 +0000 (+1100) Subject: storesms: add new functions needed by gsmd2 X-Git-Url: http://git.neil.brown.name/?a=commitdiff_plain;h=95ddfcd07e158be423b815be583a34bbcd8d00f2;p=plato.git storesms: add new functions needed by gsmd2 sms_update adds newly received messages to store if they are missing. --- diff --git a/sms/storesms.py b/sms/storesms.py index 5b63280..ea75729 100644 --- a/sms/storesms.py +++ b/sms/storesms.py @@ -482,3 +482,83 @@ class SMSstore: self.newmesg.append(tm) self.newmesg.sort() self.newmesg.reverse() + +## +# load and save lists of known SMS messages from a 'mirror' file. +def load_mirror(filename): + # load an array of index address date + # from the file and store in a hash + rv = {} + try: + f = file(filename) + except IOError: + return rv + l = f.readline() + while l: + fields = l.strip().split(None, 1) + rv[fields[0]] = fields[1] + l = f.readline() + return rv + +def save_mirror(filename, hash): + n = filename + '.new' + f = open(n, 'w') + for i in hash: + f.write(i + ' ' + hash[i] + '\n') + f.close() + os.rename(n, filename) + +def find_sms(): + pth = None + for p in ['/data','/media/card','/var/tmp']: + if os.path.exists(os.path.join(p,'SMS')): + pth = p + break + return pth + +def sms_update(messages, sim): + '''The given messages were read from the given SIM. + We need to compare against the 'mirror' for that SIM + and store any new messages in an appropriate store. + 'messages' is a hash index by message number containing + a tuple: sender, date, txt, ref, part + ''' + + path = find_sms() + if not path: + return None, None + dir = os.path.join(path, 'SMS') + store = SMSstore(dir) + mfile = os.path.join(dir, '.sim-mirror-'+sim) + mirror = load_mirror(mfile) + mirror_seen = {} + found_one = False + for index in messages: + sender, date, txt, ref, part = messages[index] + k = date[2:] + ' ' + sender + if index not in mirror or mirror[index] != k: + sms = SMSmesg(source='GSM', time=date[2:], + sender=sender, text=txt.encode('utf-8'), + state='NEW', ref=ref, part=part) + store.store(sms) + found_one = True + mirror[index] = k + mirror_seen[index] = k + + if len(mirror_seen) > 5: + save_mirror(mfile, mirror_seen) + mirror = mirror_seen + else: + save_mirror(mfile, mirror) + # Now return list that could suitably be deleted + rev = {} + dlist = [] + for i in mirror: + k = mirror[i]+' '+str(i) + rev[k] = i + dlist.append(k) + dlist.sort() + age_order = [] + for i in dlist: + age_order.append(rev[i]) + return found_one, age_order