summaryrefslogtreecommitdiff
path: root/backends/key-file/kf-persona-store.vala
blob: 3a81bdd5190b33e2cd360200133021d11a51af6e (plain)
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
/*
 * Copyright (C) 2010 Collabora Ltd.
 *
 * This library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *       Travis Reitter <travis.reitter@collabora.co.uk>
 *       Philip Withnall <philip.withnall@collabora.co.uk>
 */

using GLib;
using Folks;
using Folks.Backends.Kf;

/**
 * A persona store which is associated with a single simple key file. It will
 * create a {@link Persona} for each of the groups in the key file.
 */
public class Folks.Backends.Kf.PersonaStore : Folks.PersonaStore
{
  private HashTable<string, Persona> _personas;
  private File file;
  private GLib.KeyFile key_file;
  private uint first_unused_id = 0;

  /**
   * {@inheritDoc}
   */
  public override string type_id { get; private set; }

  /**
   * {@inheritDoc}
   */
  public override string display_name { get; private set; }

  /**
   * {@inheritDoc}
   */
  public override string id { get; private set; }

  /**
   * {@inheritDoc}
   */
  public override HashTable<string, Persona> personas
    {
      get { return this._personas; }
    }

  /**
   * Create a new PersonaStore.
   *
   * Create a new persona store to expose the {@link Persona}s provided by the
   * different groups in the key file given by `key_file`.
   */
  public PersonaStore (File key_file)
    {
      this.type_id = "key-file";
      this.id = key_file.get_basename ();
      this.display_name = this.id; /* the user should _never_ see this */
      this.trust_level = PersonaStoreTrust.FULL;
      this.file = key_file;
      this._personas = new HashTable<string, Persona> (str_hash, str_equal);
    }

  public override async void prepare ()
    {
      string filename = this.file.get_path ();
      this.key_file = new GLib.KeyFile ();

      /* Load or create the file */
      while (true)
        {
          /* Load the file; if this fails due to the file not existing or having
           * been deleted in the meantime, we can continue below and try to
           * create it instead. */
          try
            {
              string contents = null;
              size_t length = 0;

              yield this.file.load_contents_async (null, out contents,
                  out length);
              if (length > 0)
                {
                  this.key_file.load_from_data (contents, length,
                      KeyFileFlags.KEEP_COMMENTS);
                }
              break;
            }
          catch (Error e1)
            {
              if (!(e1 is IOError.NOT_FOUND))
                {
                  warning ("The relationship key file '%s' could not be " +
                      "loaded: %s", filename, e1.message);
                  this.removed ();
                  return;
                }
            }

          /* Ensure the parent directory tree exists for the new file */
          File parent_dir = this.file.get_parent ();

          try
            {
              /* Recursively create the directory */
              parent_dir.make_directory_with_parents ();
            }
          catch (Error e3)
            {
              if (!(e3 is IOError.EXISTS))
                {
                  warning ("The relationship key file directory '%s' could " +
                      "not be created: %s", parent_dir.get_path (), e3.message);
                  this.removed ();
                  return;
                }
            }

          /* Create a new file; if this fails due to the file having been
           * created in the meantime, we can loop back round and try and load
           * it. */
          try
            {
              /* Create the file */
              FileOutputStream stream = yield this.file.create_async (
                  FileCreateFlags.PRIVATE, Priority.DEFAULT);
              yield stream.close_async (Priority.DEFAULT);
            }
          catch (Error e2)
            {
              if (!(e2 is IOError.EXISTS))
                {
                  warning ("The relationship key file '%s' could not be " +
                      "created: %s", filename, e2.message);
                  this.removed ();
                  return;
                }
            }
        }

      /* We've loaded or created a key file by now, so cycle through the groups:
       * each group is a persona which we have to create and emit */
      string[] groups = this.key_file.get_groups ();
      foreach (string persona_id in groups)
        {
          if (persona_id.to_int () == this.first_unused_id)
            this.first_unused_id++;

          Persona persona = new Kf.Persona (this.key_file, persona_id, this);
          this._personas.insert (persona.iid, persona);
        }

      if (this._personas.size () > 0)
        {
          /* FIXME: Groups.ChangeReason is not the right enum to use here */
          this.personas_changed (this._personas.get_values (), null, null, null,
              Groups.ChangeReason.NONE);
        }
    }

  /**
   * {@inheritDoc}
   */
  public override async void remove_persona (Folks.Persona persona)
    {
      debug ("Removing Persona '%s' (IID '%s', group '%s')", persona.uid,
          persona.iid, persona.display_id);

      try
        {
          this.key_file.remove_group (persona.display_id);
          yield this.save_key_file ();

          /* Signal the removal of the Persona */
          GLib.List<Folks.Persona> personas = new GLib.List<Folks.Persona> ();
          personas.prepend (persona);
          this.personas_changed (null, personas, null, null, 0);
        }
      catch (KeyFileError e)
        {
          /* Ignore the error, since it's only about a missing group */
        }
    }

  /**
   * {@inheritDoc}
   */
  public override async Folks.Persona? add_persona_from_details (
      HashTable<string, Value?> details) throws Folks.PersonaStoreError
    {
      unowned Value val = details.lookup ("im-addresses");
      unowned HashTable<string, GenericArray<string>> im_addresses =
          (HashTable<string, GenericArray<string>>) val.get_boxed ();

      if (im_addresses == null || im_addresses.size () == 0)
        {
          throw new PersonaStoreError.INVALID_ARGUMENT (
              "persona store (%s, %s) requires the following details:\n" +
              "    im-addresses (provided: '%p')\n",
              this.type_id, this.id, im_addresses);
        }

      debug ("Adding Persona from details.");

      /* Find the first unused ID, taking into account that the IDs in the key
       * file may not be contiguous. */
      string persona_id = null;
      do
        {
          persona_id = this.first_unused_id.to_string ();
          this.first_unused_id++;
        }
      while (this.key_file.has_group (persona_id) == true);

      /* Create a new persona and set its im-addresses property to update the
       * key file */
      Persona persona = new Kf.Persona (this.key_file, persona_id, this);
      this._personas.insert (persona.iid, persona);
      persona.im_addresses = im_addresses;

      /* FIXME: Groups.ChangeReason is not the right enum to use here */
      GLib.List<Persona> personas = new GLib.List<Persona> ();
      personas.prepend (persona);
      this.personas_changed (personas, null, null, null,
          Groups.ChangeReason.NONE);

      return persona;
    }

  internal async void save_key_file ()
    {
      string key_file_data = this.key_file.to_data ();

      debug ("Saving key file '%s'.", this.file.get_path ());

      try
        {
          /* Note: We have to use key_file_data.size () here to get its length
           * in _bytes_ rather than _characters_. bgo#628930 */
          yield this.file.replace_contents_async (key_file_data,
              key_file_data.size (), null, false, FileCreateFlags.PRIVATE);
        }
      catch (Error e)
        {
          warning ("Could not write updated key file '%s': %s",
              this.file.get_path (), e.message);
        }
    }
}