Outils pour utilisateurs

Outils du site


Panneau latéral

scripts

Scripts personnalisés

Sauvegardes des contacts / agendas / repertoire téléphonique pour Davical

3 scripts sont nécessaires :

  • Le script global :
sauvegarde-davical.sh
#!/bin/bash
 
## répertoire de sauvegarde des contacts dans le /home :
SAUV=sauvegardes-davical
 
## répertoire contenant les listes des calendriers et annuaires :
LISTE=$HOME/bin/confs
 
## répertoire de backup sur un autre disque :
DIST=/media/data/perso/
 
## fonctions :
 
createdir(){
if [ -d $HOME/$SAUV ]
then
echo "le repertoire existe"
else
mkdir $HOME/$SAUV
fi
}
 
dump(){
davicaldump-all -d $HOME/$SAUV -a $LISTE/liste-sauv-calendriers -c $LISTE/liste-sauv-addresses -u julpec
}
 
tel(){
$HOME/bin/vcf2tel-contacts && echo "tel contact effectue"
$HOME/bin/vcf2tel-travail && echo "tel travail effectue"
}
 
backup(){
cp -R $HOME/$SAUV $DIST/$USER/ &&
cp $HOME/$SAUV/tel* $DIST/$USER/.
}
 
createdir && dump && tel && backup
  • Script de conversion .vcf à liste telephones
vcf2tel
#!/bin/bash
DAVICALUSER="nom user"
ANNUAIRE="nom-annuaire"
REPSAUV="repertoire de sauvegarde"
CONFTEX="fichier de conf pour LaTeX"
PDF="inscrire <yes> pour activer l'export en pdf et <no> pour ne pas l'activer"
 
function transvcf(){
sed -i \
    -e '1iBEGIN:VCARD\nEND:VCARD' \
    -e 's/X-EVOLUTION-UI-SLOT=[12];//' \
    $rep$vcf
}
 
function vcf2csv(){
vcf2csv-tel.py -i $rep$vcf -o $temp -d comma -q
}
 
function transcsv(){
if [ -f $temp ]
then
   cat $temp | sed '1d' | sort -n | sed -e '1iNom,Portable,Fixe' -e '/","",""/d' -e 's/"//g' -e 's/..$//' > $csv &&
   rm $temp
fi
}
 
function csv2html(){
  echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
\"ggttp://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html lang=\"fr-FR\"><head>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>
 
    <title>Téléphones $USER</title>
 
    <meta name=\"robots\" content=\"noindex,nofollow\"/>
 
  </head>" > $html
 
if [ -f $csv ]
then
(echo "<table>\
<tr align=center><td>Nom</td><td>Portable</td><td>Fixe</td></tr>" ; while read INPUT ; 
do echo "<tr><td>${INPUT//,/</td><td style=\"text-align:center;\">}</td></tr>" ; 
done < $csv ; echo "</table>") >> $html ;
sed -i '12d' $html ;
fi
}
 
function csv2pdf(){
if [ $PDF = "yes" ]
then
   cat $HOME/$CONFTEX | sed -e '/donnees/,$d' > $tex  && \
   cat $csv | sed -e 's/,/\ \&\ /g' -e 's/$/\ \\\\/' -e '1d' >> $tex && \
   cat $HOME/$CONFTEX | sed -e '1,/donnees/d' >> $tex && \
      if [ -d $reptex ]
      then
      echo "le repertoire LaTeX existe"
      else
      mkdir $reptex && cd $reptex && pdflatex $tex
      fi
   cd $reptex && pdflatex -interaction=batchmode $tex
else
exit 0
fi
}
 
 
for i in $(ls $HOME/$REPSAUV/*.vcf | grep $DAVICALUSER | grep $ANNUAIRE )
do vcf=$(basename $i)
   rep=$HOME/$REPSAUV/
   reptex="$HOME/$REPSAUV/latex"
   transvcf;
     for nom in $vcf
     do nom=${vcf%.*}
           echo $nom
       fichier=$rep$nom
                for temp in $nom
                do temp=$fichier.temp.csv
                   csv=$fichier.csv
                   html=$(echo $fichier | sed -e 's/\(.*\)\//\1\/tel-/').html
                   tex=$fichier.tex
                        vcf2csv && transcsv && csv2html && csv2pdf;
        done
      done
done
  • Script de conversion de vcf à csv :
vcf2csv.py
#!/usr/bin/python
import re
import sys
import codecs
import getopt
 
class VCFToCSVConverter:
  """
  todo: add comments to this mess
  """
  def __output( self, text ):
    if( self.quote == True ):
      self.output += '"'
    self.output += text
    if( self.quote == True ):
      self.output += '"'
    self.output += self.delimiter
 
  def __resetRow( self ):
    array = {}
    for k in self.columns:
      array[ k ] = ''
    return array
 
  def __setitem__(self, k, v ):
    self.data[ k ] = v
 
  def __getitem__(self, k):
    return self.data[ k ]
 
  def __endLine( self ):
    for k in self.columns:
      try:
        self.__output( self.data[ k ] )
      except KeyError:
        self.output += self.delimiter
    self.output += "\r\n"
    self.data = self.__resetRow()
 
  def __parseFile(self):
    try:
      inFile = codecs.open( self.inputFile , 'r', 'utf-8', 'ignore' )
      theLine = inFile.readline()
      for theLine in inFile:
        self.__parseLine( theLine )
      inFile.close()
    except IOError:
      print "error opening file.\n"
      sys.exit(2)
    outFile = codecs.open( self.outputFile, 'w', 'utf-8', 'ignore' )
    outFile.write( self.output )
    outFile.close()
 
  def __parseLine( self, theLine ):
    theLine = theLine.strip()
    if len( theLine ) < 1:
      pass
    elif re.match( '^BEGIN:VCARD', theLine ):
      pass
    elif re.match( '^END:VCARD', theLine ):
      self.__endLine()
    else:
      self.__processLine( theLine.split(":") )
 
  def __processLine( self, pieces ):
    if pieces[0] == 'ADR;TYPE=HOME':
      self.__process_address( pieces[1] )
    elif pieces[0] == 'N':
      self.__process_name( pieces[1] )
    elif pieces[0].split(";")[0] == "TEL":
      self.__process_phone( pieces[0].split(";")[1], pieces[1] )
    elif pieces[0].split(";")[0] == "EMAIL":
      self.__process_email( pieces[1] )
    elif pieces[:2] == [ 'NOTE', 'Display Name' ]:
      self.__process_display_name( pieces[2] )
 
  def __process_display_name( self, nameLine ):
    if nameLine != "%s %s" % ( self.data['First Name'], self.data['Last Name'] ):
      self.data['Display Name'] = nameLine
 
  def __process_email( self, emailLine ):
    self.data['Email'] = emailLine
 
  def __process_address( self, addressLine ):
    try:
      ( foo1, foo2, self.data['Address'], self.data['City'], self.data['State'], self.data['Zip'], self.data['Country'] ) = addressLine.split( ";" )
    except ValueError:
      print "ERROR %s " % addressLine
 
  def __process_name( self, nameLine ):
    temp = []
    try:
      ( temp ) = nameLine.split( ";" )
    except ValueError:
      print "ERROR %s " % nameLine
    if len( temp ) > 1:
      self.data['Last Name'] = temp[0]
      self.data['First Name'] = temp[1]
 
  def __process_phone( self, phoneType, phoneLine ):
    phoneType = phoneType.replace("TYPE=",'')
    if phoneType == 'CELL':
      self.data['Mobile Phone'] = phoneLine
    elif phoneType == 'HOME':
      self.data['Home Phone'] = phoneLine
    elif phoneType == 'WORK':
      self.data['Work Phone'] = phoneLine
    else:
      self.data['Other Phone'] = phoneLine
 
  def __init__( self, inputFileName, outputFileName, delimiter, quote):
    self.data = {}
    self.quote = quote
    self.delimiter = delimiter
    self.output = ''
    self.inputFile = inputFileName
    self.outputFile = outputFileName
    self.columns = (  'First Name',
                      'Last Name',
                      'Display Name',
                      'Nickname',
                      'Email',
                      'Address',
                      'City',
                      'State',
                      'Zip',
                      'Country',
                      'Home Phone',
                      'Work Phone',
                      'Mobile Phone',
                      'Other Phone',
                      'Extension',
                      'Messenger',
                      )
 
    self.data = self.__resetRow()
    for k in self.columns:
      self.__output( k )
    self.__parseFile()
 
def usage():
  print "\nCe script permet de transformer un fichier d'export de contacts (VCF) en un fichier csv\n \noptions \n-h|--help this menu\n-i input file (VCS) *required\n-o output file (TAB) *required\n-d [comma|tab|semicolon] delimiter (tab is default)\n-q double values"
 
def main():
  try:
      opts, args = getopt.getopt(sys.argv[1:], "ho:i:d:q", ["help"])
  except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
  input_file = None
  output_file = None
  quote = False
  delimiter = "\t"
  delimiter_string = "tab"
  for option, value in opts:
    if option == "-i":
      input_file = value
    elif option == "-o":
      output_file = value
    elif option == "-q":
      quote = True
    elif option == "-d":
      if value == "comma":
        delimiter = ","
        delimiter_string = "comma"
      elif value == "semicolon":
        delimiter = ";"
        delimiter_string = "semicolon"
      else:
        delimiter = "\t"
        delimiter_string = "tab"
    elif option in ("-h", "--help"):
      usage()
      sys.exit(2)
    else:
      print "unhandled option %s" % option
      sys.exit(2)
  if input_file == None or output_file == None:
    print "missing required parameters"
    usage()
    sys.exit(2)
  print "converting %s > %s (%s delimited)" % ( input_file, output_file, delimiter_string )
  VCFToCSVConverter( input_file, output_file, delimiter, quote )
  sys.exit(0)
 
if __name__ == "__main__":
  main()
  • Script de conversion vcf à csv adapté pour les téléphones uniquement :
vcf2csv-tel.py
#!/usr/bin/python
import re
import sys
import codecs
import getopt
 
class VCFToCSVConverter:
  """
  todo: add comments to this mess
  """
  def __output( self, text ):
    if( self.quote == True ):
      self.output += '"'
    self.output += text
    if( self.quote == True ):
      self.output += '"'
    self.output += self.delimiter
 
  def __resetRow( self ):
    array = {}
    for k in self.columns:
      array[ k ] = ''
    return array
 
  def __setitem__(self, k, v ):
    self.data[ k ] = v
 
  def __getitem__(self, k):
    return self.data[ k ]
 
  def __endLine( self ):
    for k in self.columns:
      try:
        self.__output( self.data[ k ] )
      except KeyError:
        self.output += self.delimiter
    self.output += "\r\n"
    self.data = self.__resetRow()
 
  def __parseFile(self):
    try:
      inFile = codecs.open( self.inputFile , 'r', 'utf-8', 'ignore' )
      theLine = inFile.readline()
      for theLine in inFile:
        self.__parseLine( theLine )
      inFile.close()
    except IOError:
      print "error opening file.\n"
      sys.exit(2)
    outFile = codecs.open( self.outputFile, 'w', 'utf-8', 'ignore' )
    outFile.write( self.output )
    outFile.close()
 
  def __parseLine( self, theLine ):
    theLine = theLine.strip()
    if len( theLine ) < 1:
      pass
    elif re.match( '^BEGIN:VCARD', theLine ):
      pass
    elif re.match( '^END:VCARD', theLine ):
      self.__endLine()
    else:
      self.__processLine( theLine.split(":") )
 
  def __processLine( self, pieces ):
    if pieces[0] == 'ADR;TYPE=HOME':
      self.__process_address( pieces[1] )
    elif pieces[0] == 'N':
      self.__process_name( pieces[1] )
    elif pieces[0].split(";")[0] == "TEL":
      self.__process_phone( pieces[0].split(";")[1], pieces[1] )
    elif pieces[0].split(";")[0] == "EMAIL":
      self.__process_email( pieces[1] )
    elif pieces[0] == 'FN':
      self.__process_display_name( pieces[1] )
 
  def __process_display_name( self, nameLine ):
    """if nameLine != "%s %s" % ( self.data['Prenom'], self.data['Nom'] ):"""
    self.data['Nom Complet'] = nameLine
 
  def __process_email( self, emailLine ):
    self.data['Email'] = emailLine
 
  def __process_address( self, addressLine ):
    try:
      ( foo1, foo2, self.data['Address'], self.data['City'], self.data['State'], self.data['Zip'], self.data['Country'] ) = addressLine.split( ";" )
    except ValueError:
      print "ERROR %s " % addressLine
 
  def __process_name( self, nameLine ):
    temp = []
    try:
      ( temp ) = nameLine.split( ";" )
    except ValueError:
      print "ERROR %s " % nameLine
    if len( temp ) > 1:
      self.data['Nom'] = temp[0]
      self.data['Prenom'] = temp[1]
 
  def __process_phone( self, phoneType, phoneLine ):
    phoneType = phoneType.replace("TYPE=",'')
    if phoneType in ('CELL','cell'):
      self.data['portable'] = phoneLine
    elif phoneType in ('home','HOME','HOME,VOICE'):
      self.data['fixe'] = phoneLine
    elif phoneType in ('work','WORK','WORK,VOICE'):
      self.data['Work Phone'] = phoneLine
    else:
      self.data['Other Phone'] = phoneLine
 
  def __init__( self, inputFileName, outputFileName, delimiter, quote):
    self.data = {}
    self.quote = quote
    self.delimiter = delimiter
    self.output = ''
    self.inputFile = inputFileName
    self.outputFile = outputFileName
    self.columns = (  'Nom Complet',
                      'portable',
                      'fixe',
                      )
 
    self.data = self.__resetRow()
    for k in self.columns:
      self.__output( k )
    self.__parseFile()
 
def usage():
  print "\n Ce script permet d'exporter les numeros de telephone d'un fichier de contacts (VCF) dans un fichier csv \n  \noptions \n-h|--help this menu\n-i input file (VCS) *required\n-o output file (TAB) *required\n-d [comma|tab|semicolon] delimiter (tab is default)\n-q double values"
 
def main():
  try:
      opts, args = getopt.getopt(sys.argv[1:], "ho:i:d:q", ["help"])
  except getopt.GetoptError, err:
    print str(err)
    usage()
    sys.exit(2)
  input_file = None
  output_file = None
  quote = False
  delimiter = "\t"
  delimiter_string = "tab"
  for option, value in opts:
    if option == "-i":
      input_file = value
    elif option == "-o":
      output_file = value
    elif option == "-q":
      quote = True
    elif option == "-d":
      if value == "comma":
        delimiter = ","
        delimiter_string = "comma"
      elif value == "semicolon":
        delimiter = ";"
        delimiter_string = "semicolon"
      else:
        delimiter = "\t"
        delimiter_string = "tab"
    elif option in ("-h", "--help"):
      usage()
      sys.exit(2)
    else:
      print "unhandled option %s" % option
      sys.exit(2)
  if input_file == None or output_file == None:
    print "missing required parameters"
    usage()
    sys.exit(2)
  print "converting %s > %s (%s delimited)" % ( input_file, output_file, delimiter_string )
  VCFToCSVConverter( input_file, output_file, delimiter, quote )
  sys.exit(0)
 
if __name__ == "__main__":
  main()
  • Script d'extraction des infos (dump) de Davical :
davicaldump-all
#!/bin/bash
 
usage()
{
cat << EOF
 
usage: $0 options
 
Ce script exporte les carnets d'addresses et les calendriers davical d'un·e utilisateur·trice.
 
Utilisation du script :
Le script a besoin de lire un fichier listant les noms des calendriers et un autre listant les noms des carnets d'addresse
 
OPTIONS :
  -u suivi du nom d'utilisateur·trice de davical
  -c suivi du fichier de carnets d'addresses
  -a suivi du fichier d'agendas
  -d suivi du dossier d'export
  -h   : affiche ce message.
EOF
}
 
agendas(){
  if [ -f $opta ]
  then
       for CAL in $(cat $opta)
       do psql davical -Atc "SELECT array_to_string(array(SELECT caldav_data FROM caldav_data WHERE dav_name LIKE '/$NAME/$CAL%'),'');" > $DIR/$CAL-$NAME.ics
       done
  else
       if [ -z $optc ]
           then echo "le fichier d'agendas ($opta) n'existe pas"
           else echo "la liste des agendas n'est pas renseignée"
       fi
  fi
}
 
contacts(){
  if [ -f $optc ]
  then
       for CARD in $(cat $optc)
       do psql davical -Atc "SELECT array_to_string(array(SELECT caldav_data FROM caldav_data WHERE dav_name LIKE '/$NAME/$CARD%'),'');" > $DIR/$CARD-$NAME.vcf
       done
  else
       if [ -z $optc ]
           then echo "la liste des carnets d'addresse n'est pas renseignée"
           else echo "le fichier de carnets d'addresses ($optc) n'existe pas"
       fi
  fi
}
 
 
NAME=
DIR=
opta=
optc=
 
if [ $# -eq 0 ]
then
        usage
fi
 
while getopts "hc:a:u:d:" option
do
 case $option in
  h) usage; exit 1 ;;
  u) NAME=$OPTARG ;;
  d) DIR=$OPTARG ;;
  a) opta=$OPTARG ;;
  c) optc=$OPTARG ;;
 esac
done
 
 
if [ -z $NAME ]
  then
     echo "il manque le nom d'utilisateur·trice"
     echo "tappez davicaldump -h pour plus d'options"
     exit 0
  else
       if [ -z $DIR ]
       then
          echo "il manque le répertoire de sauvegarde"
          echo "tappez davicaldump -h pour plus d'options"
          exit 0
       else
           if [ -d $DIR ]
	   then
	      contacts
	      agendas
           else
	      echo "le répertoire de sauvegarde n'est pas valide"
	      exit 0
           fi
        fi
fi

Sauvegarde des contacts / agendas pour Owncloud

sauvegarde-own.sh
#!/bin/bash
DATE=$(date +%F)
OCUSER="peccoud"
OCPASS="mot-de-passe"
 
# Download and gzip contacts.
rm $HOME/own/contacts-$DATE.vcf & wget --auth-no-challenge --no-clobber --http-user=$OCUSER --http-password=$OCPASS \
  -O $HOME/own/contacts-$DATE.vcf "owncloud.xilm.org/index.php/apps/contacts/export.php?bookid=2"
#gzip -f $HOME/own/contacts-$DATE.vcf
 
# Download and gzip calendar.
rm $HOME/own/calendar-$DATE.ics & wget --auth-no-challenge --no-clobber --http-user=$OCUSER --http-password=$OCPASS \
  -O $HOME/own/calendar-$DATE.ics "owncloud.xilm.org/remote.php/caldav/calendars/peccoud/defaultcalendar?export"
#gzip -f $HOME/own/calendar-$DATE.ics
scripts.txt · Dernière modification: 2015/01/05 16:00 (modification externe)