afs: Move some ls-related stuff from afs.h to aft.c.
[paraslash.git] / aft.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file aft.c Audio file table functions. */
8
9 #include "para.h"
10 #include "error.h"
11 #include <sys/mman.h>
12 #include <fnmatch.h>
13 #include "afh.h"
14 #include "afs.h"
15 #include "net.h"
16 #include "string.h"
17 #include "vss.h"
18
19 #define AFS_AUDIO_FILE_DIR "/home/mp3"
20
21 static struct osl_table *audio_file_table;
22
23 enum ls_listing_mode {
24         LS_MODE_SHORT,
25         LS_MODE_LONG,
26         LS_MODE_VERBOSE,
27         LS_MODE_MBOX
28 };
29
30 enum ls_flags {
31         LS_FLAG_FULL_PATH = 1,
32         LS_FLAG_ADMISSIBLE_ONLY = 2,
33         LS_FLAG_REVERSE = 4,
34 };
35
36 struct ls_widths {
37         unsigned short score_width;
38         unsigned short image_id_width;
39         unsigned short lyrics_id_width;
40         unsigned short bitrate_width;
41         unsigned short frequency_width;
42         unsigned short duration_width;
43         unsigned short num_played_width;
44 };
45
46 struct ls_data {
47         struct audio_format_info afhi;
48         struct afs_info afsi;
49         char *path;
50         long score;
51         HASH_TYPE *hash;
52 };
53
54 struct ls_options {
55         unsigned flags;
56         enum ls_sorting_method sorting;
57         enum ls_listing_mode mode;
58         char **patterns;
59         int num_patterns;
60         struct ls_widths widths;
61         uint32_t array_size;
62         uint32_t num_matching_paths;
63         struct ls_data *data;
64         struct ls_data **data_ptr;
65 };
66
67 /**
68  * Describes the layout of the mmapped-afs info struct.
69  *
70  * \sa struct afs_info.
71  */
72 enum afsi_offsets {
73         /** Where .last_played is stored. */
74         AFSI_LAST_PLAYED_OFFSET = 0,
75         /** Storage position of the attributes bitmap. */
76         AFSI_ATTRIBUTES_OFFSET = 8,
77         /** Storage position of the .num_played field. */
78         AFSI_NUM_PLAYED_OFFSET = 16,
79         /** Storage position of the .image_id field. */
80         AFSI_IMAGE_ID_OFFSET = 20,
81         /** Storage position of the .lyrics_id field. */
82         AFSI_LYRICS_ID_OFFSET = 24,
83         /** Storage position of the .audio_format_id field. */
84         AFSI_AUDIO_FORMAT_ID_OFFSET = 28,
85         /** On-disk storage space needed. */
86         AFSI_SIZE = 29
87 };
88
89 /**
90  * Convert a struct afs_info to an osl object.
91  *
92  * \param afsi Pointer to the audio file info to be converted.
93  * \param obj Result pointer.
94  *
95  * \sa load_afsi().
96  */
97 void save_afsi(struct afs_info *afsi, struct osl_object *obj)
98 {
99         char *buf = obj->data;
100
101         write_u64(buf + AFSI_LAST_PLAYED_OFFSET, afsi->last_played);
102         write_u64(buf + AFSI_ATTRIBUTES_OFFSET, afsi->attributes);
103         write_u32(buf + AFSI_NUM_PLAYED_OFFSET, afsi->num_played);
104         write_u32(buf + AFSI_IMAGE_ID_OFFSET, afsi->image_id);
105         write_u32(buf + AFSI_LYRICS_ID_OFFSET, afsi->lyrics_id);
106         write_u8(buf + AFSI_AUDIO_FORMAT_ID_OFFSET,
107                 afsi->audio_format_id);
108 }
109
110 /**
111  *  Get the audio file selector info struct stored in an osl object.
112  *
113  * \param afsi Points to the audio_file info structure to be filled in.
114  * \param obj The osl object holding the data.
115  *
116  * \return Positive on success, negative on errors. Possible errors: \p E_BAD_AFS.
117  *
118  * \sa save_afsi().
119  */
120 int load_afsi(struct afs_info *afsi, struct osl_object *obj)
121 {
122         char *buf = obj->data;
123         if (obj->size < AFSI_SIZE)
124                 return -E_BAD_AFSI;
125         afsi->last_played = read_u64(buf + AFSI_LAST_PLAYED_OFFSET);
126         afsi->attributes = read_u64(buf + AFSI_ATTRIBUTES_OFFSET);
127         afsi->num_played = read_u32(buf + AFSI_NUM_PLAYED_OFFSET);
128         afsi->image_id = read_u32(buf + AFSI_IMAGE_ID_OFFSET);
129         afsi->lyrics_id = read_u32(buf + AFSI_LYRICS_ID_OFFSET);
130         afsi->audio_format_id = read_u8(buf +
131                 AFSI_AUDIO_FORMAT_ID_OFFSET);
132         return 1;
133 }
134
135 /** The columns of the audio file table. */
136 enum audio_file_table_columns {
137         /** The hash on the content of the audio file. */
138         AFTCOL_HASH,
139         /** The full path in the filesystem. */
140         AFTCOL_PATH,
141         /** The audio file selector info. */
142         AFTCOL_AFSI,
143         /** The audio format handler info. */
144         AFTCOL_AFHI,
145         /** The chunk table info and the chunk table of the audio file. */
146         AFTCOL_CHUNKS,
147         /** The number of columns of this table. */
148         NUM_AFT_COLUMNS
149 };
150
151 static struct osl_column_description aft_cols[] = {
152         [AFTCOL_HASH] = {
153                 .storage_type = OSL_MAPPED_STORAGE,
154                 .storage_flags = OSL_RBTREE | OSL_FIXED_SIZE | OSL_UNIQUE,
155                 .name = "hash",
156                 .compare_function = osl_hash_compare,
157                 .data_size = HASH_SIZE
158         },
159         [AFTCOL_PATH] = {
160                 .storage_type = OSL_MAPPED_STORAGE,
161                 .storage_flags = OSL_RBTREE | OSL_UNIQUE,
162                 .name = "path",
163                 .compare_function = string_compare,
164         },
165         [AFTCOL_AFSI] = {
166                 .storage_type = OSL_MAPPED_STORAGE,
167                 .storage_flags = OSL_FIXED_SIZE,
168                 .name = "afs_info",
169                 .data_size = AFSI_SIZE
170         },
171         [AFTCOL_AFHI] = {
172                 .storage_type = OSL_MAPPED_STORAGE,
173                 .name = "afh_info",
174         },
175         [AFTCOL_CHUNKS] = {
176                 .storage_type = OSL_DISK_STORAGE,
177                 .name = "chunks",
178         }
179 };
180
181 static struct osl_table_description audio_file_table_desc = {
182         .name = "audio_files",
183         .num_columns = NUM_AFT_COLUMNS,
184         .flags = OSL_LARGE_TABLE,
185         .column_descriptions = aft_cols
186 };
187
188 static char *prefix_path(const char *prefix, int len, const char *path)
189 {
190         int speclen;
191         char *n;
192
193         for (;;) {
194                 char c;
195                 if (*path != '.')
196                         break;
197                 c = path[1];
198                 /* "." */
199                 if (!c) {
200                         path++;
201                         break;
202                 }
203                 /* "./" */
204                 if (c == '/') {
205                         path += 2;
206                         continue;
207                 }
208                 if (c != '.')
209                         break;
210                 c = path[2];
211                 if (!c)
212                         path += 2;
213                 else if (c == '/')
214                         path += 3;
215                 else
216                         break;
217                 /* ".." and "../" */
218                 /* Remove last component of the prefix */
219                 do {
220                         if (!len)
221                                 return NULL;
222                         len--;
223                 } while (len && prefix[len-1] != '/');
224                 continue;
225         }
226         if (!len)
227                 return para_strdup(path);
228         speclen = strlen(path);
229         n = para_malloc(speclen + len + 1);
230         memcpy(n, prefix, len);
231         memcpy(n + len, path, speclen+1);
232         return n;
233 }
234
235 /*
236  * We fundamentally don't like some paths: we don't want
237  * dot or dot-dot anywhere.
238  *
239  * Also, we don't want double slashes or slashes at the
240  * end that can make pathnames ambiguous.
241  */
242 static int verify_dotfile(const char *rest)
243 {
244         /*
245          * The first character was '.', but that has already been discarded, we
246          * now test the rest.
247          */
248         switch (*rest) {
249         /* "." is not allowed */
250         case '\0': case '/':
251                 return 1;
252
253         case '.':
254                 if (rest[1] == '\0' || rest[1] == '/')
255                         return -1;
256         }
257         return 1;
258 }
259
260 static int verify_path(const char *orig_path, char **resolved_path)
261 {
262         char c;
263         const char prefix[] = AFS_AUDIO_FILE_DIR "/";
264         const char *path = orig_path;
265         const size_t prefix_len = strlen(prefix);
266
267         c = *path++;
268         if (!c)
269                 goto bad_path;
270         while (c) {
271                 if (c == '/') {
272                         c = *path++;
273                         switch (c) {
274                         default:
275                                 continue;
276                         case '/': /* double slash */
277                                 goto bad_path;
278                         case '.':
279                                 if (verify_dotfile(path) < 0)
280                                         goto bad_path;
281                         }
282                 }
283                 c = *path++;
284         }
285         if (*orig_path != '/')
286                 *resolved_path = prefix_path(prefix, prefix_len, orig_path);
287         else
288                 *resolved_path = para_strdup(orig_path);
289         return 1;
290 bad_path:
291         return -E_BAD_PATH;
292 }
293
294 enum afhi_offsets {
295         AFHI_SECONDS_TOTAL_OFFSET = 0,
296         AFHI_BITRATE_OFFSET = 4,
297         AFHI_FREQUENCY_OFFSET = 8,
298         AFHI_CHANNELS_OFFSET = 12,
299         AFHI_INFO_STRING_OFFSET = 13,
300         MIN_AFHI_SIZE = 14
301 };
302
303 static unsigned sizeof_afhi_buf(const struct audio_format_info *afhi)
304 {
305         if (!afhi)
306                 return 0;
307         return strlen(afhi->info_string) + MIN_AFHI_SIZE;
308 }
309
310 static void save_afhi(struct audio_format_info *afhi, char *buf)
311 {
312         if (!afhi)
313                 return;
314         write_u32(buf + AFHI_SECONDS_TOTAL_OFFSET,
315                 afhi->seconds_total);
316         write_u32(buf + AFHI_BITRATE_OFFSET, afhi->bitrate);
317         write_u32(buf + AFHI_FREQUENCY_OFFSET, afhi->frequency);
318         write_u8(buf + AFHI_CHANNELS_OFFSET, afhi->channels);
319         strcpy(buf + AFHI_INFO_STRING_OFFSET, afhi->info_string); /* OK */
320         PARA_DEBUG_LOG("last byte written: %p\n", buf + AFHI_INFO_STRING_OFFSET + strlen(afhi->info_string));
321 }
322
323 static void load_afhi(const char *buf, struct audio_format_info *afhi)
324 {
325         afhi->seconds_total = read_u32(buf + AFHI_SECONDS_TOTAL_OFFSET);
326         afhi->bitrate = read_u32(buf + AFHI_BITRATE_OFFSET);
327         afhi->frequency = read_u32(buf + AFHI_FREQUENCY_OFFSET);
328         afhi->channels = read_u8(buf + AFHI_CHANNELS_OFFSET);
329         strcpy(afhi->info_string, buf + AFHI_INFO_STRING_OFFSET);
330 }
331
332 static unsigned sizeof_chunk_info_buf(struct audio_format_info *afhi)
333 {
334         if (!afhi)
335                 return 0;
336         return 4 * afhi->chunks_total + 20;
337
338 }
339
340 /** The offsets of the data contained in the AFTCOL_CHUNKS column. */
341 enum chunk_info_offsets{
342         /** The total number of chunks (4 bytes). */
343         CHUNKS_TOTAL_OFFSET = 0,
344         /** The length of the audio file header (4 bytes). */
345         HEADER_LEN_OFFSET = 4,
346         /** The start of the audio file header (4 bytes). */
347         HEADER_OFFSET_OFFSET = 8,
348         /** The seconds part of the chunk time (4 bytes). */
349         CHUNK_TV_TV_SEC_OFFSET = 12,
350         /** The microseconds part of the chunk time (4 bytes). */
351         CHUNK_TV_TV_USEC = 16,
352         /** Chunk table entries start here. */
353         CHUNK_TABLE_OFFSET = 20,
354 };
355
356 /* TODO: audio format handlers could just produce this */
357 static void save_chunk_info(struct audio_format_info *afhi, char *buf)
358 {
359         int i;
360
361         if (!afhi)
362                 return;
363         write_u32(buf + CHUNKS_TOTAL_OFFSET, afhi->chunks_total);
364         write_u32(buf + HEADER_LEN_OFFSET, afhi->header_len);
365         write_u32(buf + HEADER_OFFSET_OFFSET, afhi->header_offset);
366         write_u32(buf + CHUNK_TV_TV_SEC_OFFSET, afhi->chunk_tv.tv_sec);
367         write_u32(buf + CHUNK_TV_TV_USEC, afhi->chunk_tv.tv_usec);
368         for (i = 0; i < afhi->chunks_total; i++)
369                 write_u32(buf + CHUNK_TABLE_OFFSET + 4 * i, afhi->chunk_table[i]);
370 }
371
372 static int load_chunk_info(struct osl_object *obj, struct audio_format_info *afhi)
373 {
374         char *buf = obj->data;
375         int i;
376
377         if (obj->size < CHUNK_TABLE_OFFSET)
378                 return -E_BAD_DATA_SIZE;
379
380         afhi->chunks_total = read_u32(buf + CHUNKS_TOTAL_OFFSET);
381         afhi->header_len = read_u32(buf + HEADER_LEN_OFFSET);
382         afhi->header_offset = read_u32(buf + HEADER_OFFSET_OFFSET);
383         afhi->chunk_tv.tv_sec = read_u32(buf + CHUNK_TV_TV_SEC_OFFSET);
384         afhi->chunk_tv.tv_usec = read_u32(buf + CHUNK_TV_TV_USEC);
385
386         if (afhi->chunks_total * 4 + CHUNK_TABLE_OFFSET > obj->size)
387                 return -E_BAD_DATA_SIZE;
388         afhi->chunk_table = para_malloc(afhi->chunks_total * sizeof(size_t));
389         for (i = 0; i < afhi->chunks_total; i++)
390                 afhi->chunk_table[i] = read_u32(buf + CHUNK_TABLE_OFFSET + 4 * i);
391         return 1;
392 }
393
394 /**
395  * Get the row of the audio file table corresponding to the given path.
396  *
397  * \param path The full path of the audio file.
398  * \param row Result pointer.
399  *
400  * \return The return value of the underlying call to osl_get_row().
401  */
402 int aft_get_row_of_path(char *path, struct osl_row **row)
403 {
404         struct osl_object obj = {.data = path, .size = strlen(path) + 1};
405
406         return osl_get_row(audio_file_table, AFTCOL_PATH, &obj, row);
407 }
408
409 /**
410  * Get the row of the audio file table corresponding to the given hash value.
411  *
412  * \param hash The hash value of the desired audio file.
413  * \param row resul pointer.
414  *
415  * \return The return value of the underlying call to osl_get_row().
416  */
417 int aft_get_row_of_hash(HASH_TYPE *hash, struct osl_row **row)
418 {
419         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
420         return osl_get_row(audio_file_table, AFTCOL_HASH, &obj, row);
421 }
422
423 /**
424  * Get the osl object holding the audio file selector info of a row.
425  *
426  * \param row Pointer to a row in the audio file table.
427  * \param obj Result pointer.
428  *
429  * \return The return value of the underlying call to osl_get_object().
430  */
431 int get_afsi_object_of_row(const struct osl_row *row, struct osl_object *obj)
432 {
433         return osl_get_object(audio_file_table, row, AFTCOL_AFSI, obj);
434 }
435
436 /**
437  * Get the osl object holding the audio file selector info, given a path.
438  *
439  *
440  * \param path The full path of the audio file.
441  * \param obj Result pointer.
442  *
443  * \return Positive on success, negative on errors.
444  */
445 int get_afsi_object_of_path(char *path, struct osl_object *obj)
446 {
447         struct osl_row *row;
448         int ret = aft_get_row_of_path(path, &row);
449         if (ret < 0)
450                 return ret;
451         return get_afsi_object_of_row(row, obj);
452 }
453
454 /**
455  * Get the audio file selector info, given a row of the audio file table.
456  *
457  * \param row Pointer to a row in the audio file table.
458  * \param afsi Result pointer.
459  *
460  * \return Positive on success, negative on errors.
461  */
462 int get_afsi_of_row(const struct osl_row *row, struct afs_info *afsi)
463 {
464         struct osl_object obj;
465         int ret = get_afsi_object_of_row(row, &obj);
466         if (ret < 0)
467                 return ret;
468         return load_afsi(afsi, &obj);
469 }
470
471 /**
472  * Get the path of an audio file, given a row of the audio file table.
473  *
474  * \param row Pointer to a row in the audio file table.
475  * \param path Result pointer.
476  *
477  * \return Positive on success, negative on errors.
478  */
479 int get_audio_file_path_of_row(const struct osl_row *row, char **path)
480 {
481         struct osl_object path_obj;
482         int ret = osl_get_object(audio_file_table, row, AFTCOL_PATH,
483                 &path_obj);
484         if (ret < 0)
485                 return ret;
486         *path = path_obj.data;
487         return 1;
488 }
489
490 /**
491  * Get the object containing the hash value of an audio file, given a row.
492  *
493  * \param row Pointer to a row of the audio file table.
494  * \param obj Result pointer.
495  *
496  * \return The return value of the underlying call to osl_get_object().
497  *
498  * \sa get_hash_of_row().
499  */
500 static int get_hash_object_of_aft_row(const struct osl_row *row, struct osl_object *obj)
501 {
502         return osl_get_object(audio_file_table, row, AFTCOL_HASH, obj);
503 }
504
505 /**
506  * Get the hash value of an audio file, given a row of the audio file table.
507  *
508  * \param row Pointer to a row of the audio file table.
509  * \param hash Result pointer.
510  *
511  * \a hash points to mapped data and must not be freed by the caller.
512  *
513  * \return The return value of the underlying call to
514  * get_hash_object_of_aft_row().
515  */
516 static int get_hash_of_row(const struct osl_row *row, HASH_TYPE **hash)
517 {
518         struct osl_object obj;
519         int ret = get_hash_object_of_aft_row(row, &obj);
520
521         if (ret < 0)
522                 return ret;
523         *hash = obj.data;
524         return 1;
525 }
526
527 /**
528  * Get the audio format handler info, given a row of the audio file table.
529  *
530  * \param row Pointer to a row of the audio file table.
531  * \param afhi Result pointer.
532  *
533  * \return The return value of the underlying call to osl_get_object().
534  *
535  * \sa get_chunk_table_of_row().
536  */
537 static int get_afhi_of_row(const struct osl_row *row, struct audio_format_info *afhi)
538 {
539         struct osl_object obj;
540         int ret = osl_get_object(audio_file_table, row, AFTCOL_AFHI,
541                 &obj);
542         if (ret < 0)
543                 return ret;
544         load_afhi(obj.data, afhi);
545         return 1;
546 }
547
548 /**
549  * Get the chunk table of an audio file, given a row of the audio file table.
550  *
551  * \param row Pointer to a row of the audio file table.
552  * \param afhi Result pointer.
553  *
554  * \return The return value of the underlying call to osl_open_disk_object().
555  *
556  * \sa get_afhi_of_row().
557  */
558 static int get_chunk_table_of_row(const struct osl_row *row, struct audio_format_info *afhi)
559 {
560         struct osl_object obj;
561         int ret = osl_open_disk_object(audio_file_table, row, AFTCOL_CHUNKS,
562                 &obj);
563         if (ret < 0)
564                 return ret;
565         ret = load_chunk_info(&obj, afhi);
566         osl_close_disk_object(&obj);
567         return ret;
568 }
569
570 /**
571  * Mmap the given audio file and update statistics.
572  *
573  * \param aft_row Determines the audio file to be opened and updated.
574  * \param afd Result pointer.
575  *
576  * On success, the numplayed field of the audio file selector info is increased
577  * and the lastplayed time is set to the current time. Finally, the score of
578  * the audio file is updated.
579  *
580  * \return Positive on success, negative on errors.
581  */
582 int open_and_update_audio_file(struct osl_row *aft_row, struct audio_file_data *afd)
583 {
584         HASH_TYPE *aft_hash, file_hash[HASH_SIZE];
585         struct osl_object afsi_obj;
586         struct afs_info new_afsi;
587         int ret = get_hash_of_row(aft_row, &aft_hash);
588
589         if (ret < 0)
590                 return ret;
591         ret = get_audio_file_path_of_row(aft_row, &afd->path);
592         if (ret < 0)
593                 return ret;
594         ret = get_afsi_object_of_row(aft_row, &afsi_obj);
595         if (ret < 0)
596                 return ret;
597         ret = load_afsi(&afd->afsi, &afsi_obj);
598         if (ret < 0)
599                 return ret;
600         ret = get_afhi_of_row(aft_row, &afd->afhi);
601         if (ret < 0)
602                 return ret;
603         ret = get_chunk_table_of_row(aft_row, &afd->afhi);
604         if (ret < 0)
605                 return ret;
606         ret = mmap_full_file(afd->path, O_RDONLY, &afd->map);
607         if (ret < 0)
608                 goto err;
609         hash_function(afd->map.data, afd->map.size, file_hash);
610         ret = -E_HASH_MISMATCH;
611         if (hash_compare(file_hash, aft_hash))
612                 goto err;
613         new_afsi = afd->afsi;
614         new_afsi.num_played++;
615         new_afsi.last_played = time(NULL);
616         save_afsi(&new_afsi, &afsi_obj); /* in-place update */
617         if (afd->current_play_mode == PLAY_MODE_PLAYLIST)
618                 ret = playlist_update_audio_file(aft_row);
619         else
620                 ret = mood_update_audio_file(aft_row, &afd->afsi);
621         return ret;
622 err:
623         free(afd->afhi.chunk_table);
624         return ret;
625 }
626
627 static int get_local_time(uint64_t *seconds, char *buf, size_t size,
628         time_t current_time)
629 {
630         struct tm t;
631
632         if (!localtime_r((time_t *)seconds, &t))
633                 return -E_LOCALTIME;
634         if (*seconds + 6 * 30 * 24 * 3600 > current_time) {
635                 if (!strftime(buf, size, "%b %e %k:%M", &t))
636                         return -E_STRFTIME;
637                 return 1;
638         }
639         if (!strftime(buf, size, "%b %e  %Y", &t))
640                 return -E_STRFTIME;
641         return 1;
642 }
643
644 #define GET_NUM_DIGITS(x, num) { \
645         typeof((x)) _tmp = PARA_ABS(x); \
646         *num = 1; \
647         if ((x)) \
648                 while ((_tmp) > 9) { \
649                         (_tmp) /= 10; \
650                         (*num)++; \
651                 } \
652         }
653
654 static short unsigned get_duration_width(int seconds)
655 {
656         short unsigned width;
657         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
658
659         if (!hours) /* less than one hour => m:ss or mm:ss => 4 or 5 digits */
660                 return 4 + (mins > 9);
661         /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
662         GET_NUM_DIGITS(hours, &width);
663         return width + 6;
664 }
665
666 static void get_duration_buf(int seconds, char *buf, short unsigned max_width)
667 {
668         unsigned hours = seconds / 3600, mins = (seconds % 3600) / 60;
669
670         if (!hours) /* m:ss or mm:ss */
671                 sprintf(buf, "%*u:%02u", max_width - 3, mins, seconds % 60);
672         else /* more than one hour => h:mm:ss, hh:mm:ss, hhh:mm:ss, ... */
673                 sprintf(buf, "%*u:%02u:%02u", max_width - 6, hours, mins,
674                         seconds % 60);
675 }
676
677 static char *make_attribute_line(const char *att_bitmap, struct afs_info *afsi)
678 {
679         char *att_text, *att_line;
680
681         get_attribute_text(&afsi->attributes, " ", &att_text);
682         if (!att_text)
683                 return para_strdup(att_bitmap);
684         att_line = make_message("%s (%s)", att_bitmap, att_text);
685         free(att_text);
686         return att_line;
687 }
688
689 static char *make_lyrics_line(struct afs_info *afsi)
690 {
691         char *lyrics_name;
692         lyr_get_name_by_id(afsi->lyrics_id, &lyrics_name);
693         if (!lyrics_name)
694                 return make_message("%u", afsi->lyrics_id);
695         return make_message("%u (%s)", afsi->lyrics_id, lyrics_name);
696 }
697
698 static char *make_image_line(struct afs_info *afsi)
699 {
700         char *image_name;
701         img_get_name_by_id(afsi->image_id, &image_name);
702         if (!image_name)
703                 return make_message("%u", afsi->image_id);
704         return make_message("%u (%s)", afsi->image_id, image_name);
705 }
706
707 static int print_list_item(struct ls_data *d, struct ls_options *opts,
708         struct para_buffer *b, time_t current_time)
709 {
710         int ret;
711         char att_buf[65];
712         char last_played_time[30];
713         char duration_buf[30]; /* nobody has an audio file long enough to overflow this */
714         char score_buf[30] = "";
715         struct afs_info *afsi = &d->afsi;
716         struct audio_format_info *afhi = &d->afhi;
717         struct ls_widths *w = &opts->widths;
718         int have_score = opts->flags & LS_FLAG_ADMISSIBLE_ONLY;
719
720         if (opts->mode == LS_MODE_SHORT) {
721                 para_printf(b, "%s\n", d->path);
722                 return 1;
723         }
724         get_attribute_bitmap(&afsi->attributes, att_buf);
725         ret = get_local_time(&afsi->last_played, last_played_time,
726                 sizeof(last_played_time), current_time);
727         if (ret < 0)
728                 return ret;
729         get_duration_buf(afhi->seconds_total, duration_buf, w->duration_width);
730         if (have_score) {
731                 if (opts->mode == LS_MODE_LONG)
732                         sprintf(score_buf, "%*li ", w->score_width, d->score);
733                 else
734                         sprintf(score_buf, "%li ", d->score);
735         }
736
737         PARA_NOTICE_LOG("id: %s, %d\n", d->path, afsi->audio_format_id);
738         if (opts->mode == LS_MODE_LONG) {
739                 para_printf(b,
740                         "%s"    /* score */
741                         "%s "   /* attributes */
742                         "%*d "  /* image_id  */
743                         "%*d "  /* lyrics_id */
744                         "%*d "  /* bitrate */
745                         "%s "   /* audio format */
746                         "%*d "  /* frequency */
747                         "%d "   /* channels */
748                         "%s "   /* duration */
749                         "%*d "  /* num_played */
750                         "%s "   /* last_played */
751                         "%s\n", /* path */
752                         score_buf,
753                         att_buf,
754                         w->image_id_width, afsi->image_id,
755                         w->lyrics_id_width, afsi->lyrics_id,
756                         w->bitrate_width, afhi->bitrate,
757                         audio_format_name(afsi->audio_format_id),
758                         w->frequency_width, afhi->frequency,
759                         afhi->channels,
760                         duration_buf,
761                         w->num_played_width, afsi->num_played,
762                         last_played_time,
763                         d->path
764                 );
765                 return 1;
766         }
767         if (opts->mode == LS_MODE_VERBOSE) {
768                 char asc_hash[2 * HASH_SIZE + 1];
769                 char *att_line, *lyrics_line, *image_line;
770
771                 hash_to_asc(d->hash, asc_hash);
772                 att_line = make_attribute_line(att_buf, afsi);
773                 lyrics_line = make_lyrics_line(afsi);
774                 image_line = make_image_line(afsi);
775                 para_printf(b,
776                         "%s: %s\n" /* path */
777                         "%s%s%s" /* score */
778                         "attributes: %s\n"
779                         "hash: %s\n"
780                         "image_id: %s\n"
781                         "lyrics_id: %s\n"
782                         "bitrate: %dkbit/s\n"
783                         "format: %s\n"
784                         "frequency: %dHz\n"
785                         "channels: %d\n"
786                         "duration: %s\n"
787                         "num_played: %d\n"
788                         "last_played: %s\n\n",
789                         (opts->flags & LS_FLAG_FULL_PATH)?
790                                 "path" : "file", d->path,
791                         have_score? "score: " : "", score_buf,
792                                 have_score? "\n" : "",
793                         att_line,
794                         asc_hash,
795                         image_line,
796                         lyrics_line,
797                         afhi->bitrate,
798                         audio_format_name(afsi->audio_format_id),
799                         afhi->frequency,
800                         afhi->channels,
801                         duration_buf,
802                         afsi->num_played,
803                         last_played_time
804                 );
805                 free(att_line);
806                 free(lyrics_line);
807                 free(image_line);
808                 return 1;
809         }
810         return 1;
811 }
812
813 static int ls_audio_format_compare(const void *a, const void *b)
814 {
815         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
816         return NUM_COMPARE(d1->afsi.audio_format_id, d2->afsi.audio_format_id);
817 }
818
819 static int ls_duration_compare(const void *a, const void *b)
820 {
821         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
822         return NUM_COMPARE(d1->afhi.seconds_total, d2->afhi.seconds_total);
823 }
824
825 static int ls_bitrate_compare(const void *a, const void *b)
826 {
827         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
828         return NUM_COMPARE(d1->afhi.bitrate, d2->afhi.bitrate);
829 }
830
831 static int ls_lyrics_id_compare(const void *a, const void *b)
832 {
833         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
834         return NUM_COMPARE(d1->afsi.lyrics_id, d2->afsi.lyrics_id);
835 }
836
837 static int ls_image_id_compare(const void *a, const void *b)
838 {
839         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
840         return NUM_COMPARE(d1->afsi.image_id, d2->afsi.image_id);
841 }
842
843 static int ls_channels_compare(const void *a, const void *b)
844 {
845         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
846         return NUM_COMPARE(d1->afhi.channels, d2->afhi.channels);
847 }
848
849 static int ls_frequency_compare(const void *a, const void *b)
850 {
851         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
852         return NUM_COMPARE(d1->afhi.frequency, d2->afhi.frequency);
853 }
854
855 static int ls_num_played_compare(const void *a, const void *b)
856 {
857         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
858         return NUM_COMPARE(d1->afsi.num_played, d2->afsi.num_played);
859 }
860
861 static int ls_last_played_compare(const void *a, const void *b)
862 {
863         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
864         return NUM_COMPARE(d1->afsi.last_played, d2->afsi.last_played);
865 }
866
867 static int ls_score_compare(const void *a, const void *b)
868 {
869         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
870         return NUM_COMPARE(d1->score, d2->score);
871 }
872
873 static int ls_path_compare(const void *a, const void *b)
874 {
875         struct ls_data *d1 = *(struct ls_data **)a, *d2 = *(struct ls_data **)b;
876         return strcmp(d1->path, d2->path);
877 }
878
879 static int sort_matching_paths(struct ls_options *options)
880 {
881         size_t nmemb = options->num_matching_paths;
882         size_t size = sizeof(*options->data_ptr);
883         int (*compar)(const void *, const void *);
884         int i;
885
886         options->data_ptr = para_malloc(nmemb * sizeof(*options->data_ptr));
887         for (i = 0; i < nmemb; i++)
888                 options->data_ptr[i] = options->data + i;
889
890         /* In these cases the array is already sorted */
891         if (options->sorting == LS_SORT_BY_PATH
892                 && !(options->flags & LS_FLAG_ADMISSIBLE_ONLY)
893                 && (options->flags & LS_FLAG_FULL_PATH))
894                 return 1;
895         if (options->sorting == LS_SORT_BY_SCORE &&
896                         options->flags & LS_FLAG_ADMISSIBLE_ONLY)
897                 return 1;
898
899         switch (options->sorting) {
900         case LS_SORT_BY_PATH:
901                 compar = ls_path_compare; break;
902         case LS_SORT_BY_SCORE:
903                 compar = ls_score_compare; break;
904         case LS_SORT_BY_LAST_PLAYED:
905                 compar = ls_last_played_compare; break;
906         case LS_SORT_BY_NUM_PLAYED:
907                 compar = ls_num_played_compare; break;
908         case LS_SORT_BY_FREQUENCY:
909                 compar = ls_frequency_compare; break;
910         case LS_SORT_BY_CHANNELS:
911                 compar = ls_channels_compare; break;
912         case LS_SORT_BY_IMAGE_ID:
913                 compar = ls_image_id_compare; break;
914         case LS_SORT_BY_LYRICS_ID:
915                 compar = ls_lyrics_id_compare; break;
916         case LS_SORT_BY_BITRATE:
917                 compar = ls_bitrate_compare; break;
918         case LS_SORT_BY_DURATION:
919                 compar = ls_duration_compare; break;
920         case LS_SORT_BY_AUDIO_FORMAT:
921                 compar = ls_audio_format_compare; break;
922         default:
923                 return -E_BAD_SORT;
924         }
925         qsort(options->data_ptr, nmemb, size, compar);
926         return 1;
927 }
928
929 /* row is either an aft_row or a row of the score table */
930 /* TODO: Only compute widths if we need them */
931 static int prepare_ls_row(struct osl_row *row, void *ls_opts)
932 {
933         int ret, i;
934         struct ls_options *options = ls_opts;
935         struct ls_data *d;
936         struct ls_widths *w;
937         unsigned short num_digits;
938         unsigned tmp;
939         struct osl_row *aft_row;
940         long score;
941         char *path;
942
943         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
944                 ret = get_score_and_aft_row(row, &score, &aft_row);
945                 if (ret < 0)
946                         return ret;
947         } else
948                 aft_row = row;
949         ret = get_audio_file_path_of_row(aft_row, &path);
950         if (ret < 0)
951                 return ret;
952         if (!(options->flags & LS_FLAG_FULL_PATH)) {
953                 char *p = strrchr(path, '/');
954                 if (p)
955                         path = p + 1;
956         }
957         if (options->num_patterns) {
958                 for (i = 0; i < options->num_patterns; i++) {
959                         ret = fnmatch(options->patterns[i], path, FNM_PATHNAME);
960                         if (!ret)
961                                 break;
962                         if (ret == FNM_NOMATCH)
963                                 continue;
964                         return -E_FNMATCH;
965                 }
966                 if (i >= options->num_patterns) /* no match */
967                         return 1;
968         }
969         tmp = options->num_matching_paths++;
970         if (options->num_matching_paths > options->array_size) {
971                 options->array_size++;
972                 options->array_size *= 2;
973                 options->data = para_realloc(options->data, options->array_size
974                         * sizeof(*options->data));
975         }
976         d = options->data + tmp;
977         ret = get_afsi_of_row(aft_row, &d->afsi);
978         if (ret < 0)
979                 return ret;
980         ret = get_afhi_of_row(aft_row, &d->afhi);
981         if (ret < 0)
982                 return ret;
983         d->path = path;
984         ret = get_hash_of_row(aft_row, &d->hash);
985         if (ret < 0)
986                 return ret;
987         w = &options->widths;
988         GET_NUM_DIGITS(d->afsi.image_id, &num_digits);
989         w->image_id_width = PARA_MAX(w->image_id_width, num_digits);
990         GET_NUM_DIGITS(d->afsi.lyrics_id, &num_digits);
991         w->lyrics_id_width = PARA_MAX(w->lyrics_id_width, num_digits);
992         GET_NUM_DIGITS(d->afhi.bitrate, &num_digits);
993         w->bitrate_width = PARA_MAX(w->bitrate_width, num_digits);
994         GET_NUM_DIGITS(d->afhi.frequency, &num_digits);
995         w->frequency_width = PARA_MAX(w->frequency_width, num_digits);
996         GET_NUM_DIGITS(d->afsi.num_played, &num_digits);
997         w->num_played_width = PARA_MAX(w->num_played_width, num_digits);
998         /* get the number of chars to print this amount of time */
999         tmp = get_duration_width(d->afhi.seconds_total);
1000         w->duration_width = PARA_MAX(w->duration_width, tmp);
1001         if (options->flags & LS_FLAG_ADMISSIBLE_ONLY) {
1002                 GET_NUM_DIGITS(score, &num_digits);
1003                 num_digits++; /* add one for the sign (space or "-") */
1004                 w->score_width = PARA_MAX(w->score_width, num_digits);
1005                 d->score = score;
1006         }
1007         return 1;
1008 }
1009
1010 static int com_ls_callback(const struct osl_object *query,
1011                 struct osl_object *ls_output)
1012 {
1013         struct ls_options *opts = query->data;
1014         char *p, *pattern_start = (char *)query->data + sizeof(*opts);
1015         struct para_buffer b = {.buf = NULL, .size = 0};
1016         int i = 0, ret;
1017         time_t current_time;
1018
1019
1020         PARA_NOTICE_LOG("%d patterns\n", opts->num_patterns);
1021         if (opts->num_patterns) {
1022                 opts->patterns = para_malloc(opts->num_patterns * sizeof(char *));
1023                 for (i = 0, p = pattern_start; i < opts->num_patterns; i++) {
1024                         opts->patterns[i] = p;
1025                         p += strlen(p) + 1;
1026                         PARA_NOTICE_LOG("pattern %d: %s\n", i, opts->patterns[i]);
1027                 }
1028         } else
1029                 opts->patterns = NULL;
1030         if (opts->flags & LS_FLAG_ADMISSIBLE_ONLY)
1031                 ret = admissible_file_loop(opts, prepare_ls_row);
1032         else
1033                 ret = osl_rbtree_loop(audio_file_table, AFTCOL_PATH, opts,
1034                         prepare_ls_row);
1035         if (ret < 0)
1036                 goto out;
1037         ret = opts->num_patterns? -E_NO_MATCH : 0;
1038         if (!opts->num_matching_paths) {
1039                 PARA_NOTICE_LOG("no match, ret: %d\n", ret);
1040                 goto out;
1041         }
1042         ret = sort_matching_paths(opts);
1043         if (ret < 0)
1044                 goto out;
1045         time(&current_time);
1046         if (opts->flags & LS_FLAG_REVERSE)
1047                 for (i = opts->num_matching_paths - 1; i >= 0; i--) {
1048                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1049                         if (ret < 0)
1050                                 break;
1051                 }
1052         else
1053                 for (i = 0; i < opts->num_matching_paths; i++) {
1054                         ret = print_list_item(opts->data_ptr[i], opts, &b, current_time);
1055                         if (ret < 0)
1056                                 break;
1057                 }
1058         ret = 1;
1059 out:
1060         ls_output->data = b.buf;
1061         PARA_NOTICE_LOG("ls_outoute.data: %p\n", ls_output->data);
1062         ls_output->size = b.size;
1063         free(opts->data);
1064         free(opts->data_ptr);
1065         free(opts->patterns);
1066         return ret;
1067 }
1068
1069 /*
1070  * TODO: flags -h (sort by hash) -lm (list in mbox format)
1071  *
1072  * long list: list hash, attributes as (xx--x-x-), file size, lastplayed
1073  * full list: list everything, including afsi, afhi, atts as clear text
1074  *
1075  * */
1076 int com_afs_ls(int fd, int argc, char * const * const argv)
1077 {
1078         int i, ret;
1079         unsigned flags = 0;
1080         enum ls_sorting_method sort = LS_SORT_BY_PATH;
1081         enum ls_listing_mode mode = LS_MODE_SHORT;
1082         struct ls_options opts = {.patterns = NULL};
1083         struct osl_object query = {.data = &opts, .size = sizeof(opts)},
1084                 ls_output;
1085
1086         for (i = 1; i < argc; i++) {
1087                 const char *arg = argv[i];
1088                 if (arg[0] != '-')
1089                         break;
1090                 if (!strcmp(arg, "--")) {
1091                         i++;
1092                         break;
1093                 }
1094                 if (!strncmp(arg, "-l", 2)) {
1095                         if (!*(arg + 2)) {
1096                                 mode = LS_MODE_LONG;
1097                                 continue;
1098                         }
1099                         if (*(arg + 3))
1100                                 return -E_AFT_SYNTAX;
1101                         switch(*(arg + 2)) {
1102                         case 's':
1103                                 mode = LS_MODE_SHORT;
1104                                 continue;
1105                         case 'l':
1106                                 mode = LS_MODE_LONG;
1107                                 continue;
1108                         case 'v':
1109                                 mode = LS_MODE_VERBOSE;
1110                                 continue;
1111                         case 'm':
1112                                 mode = LS_MODE_MBOX;
1113                                 continue;
1114                         default:
1115                                 return -E_AFT_SYNTAX;
1116                         }
1117                 }
1118                 if (!strcmp(arg, "-p")) {
1119                         flags |= LS_FLAG_FULL_PATH;
1120                         continue;
1121                 }
1122                 if (!strcmp(arg, "-a")) {
1123                         flags |= LS_FLAG_ADMISSIBLE_ONLY;
1124                         continue;
1125                 }
1126                 if (!strcmp(arg, "-r")) {
1127                         flags |= LS_FLAG_REVERSE;
1128                         continue;
1129                 }
1130                 if (!strncmp(arg, "-s", 2)) {
1131                         if (!*(arg + 2) || *(arg + 3))
1132                                 return -E_AFT_SYNTAX;
1133                         switch(*(arg + 2)) {
1134                         case 'p':
1135                                 sort = LS_SORT_BY_PATH;
1136                                 continue;
1137                         case 's': /* -ss implies -a */
1138                                 sort = LS_SORT_BY_SCORE;
1139                                 flags |= LS_FLAG_ADMISSIBLE_ONLY;
1140                                 continue;
1141                         case 'l':
1142                                 sort = LS_SORT_BY_LAST_PLAYED;
1143                                 continue;
1144                         case 'n':
1145                                 sort = LS_SORT_BY_NUM_PLAYED;
1146                                 continue;
1147                         case 'f':
1148                                 sort = LS_SORT_BY_FREQUENCY;
1149                                 continue;
1150                         case 'c':
1151                                 sort = LS_SORT_BY_CHANNELS;
1152                                 continue;
1153                         case 'i':
1154                                 sort = LS_SORT_BY_IMAGE_ID;
1155                                 continue;
1156                         case 'y':
1157                                 sort = LS_SORT_BY_LYRICS_ID;
1158                                 continue;
1159                         case 'b':
1160                                 sort = LS_SORT_BY_BITRATE;
1161                                 continue;
1162                         case 'd':
1163                                 sort = LS_SORT_BY_DURATION;
1164                                 continue;
1165                         case 'a':
1166                                 sort = LS_SORT_BY_AUDIO_FORMAT;
1167                                 continue;
1168                         default:
1169                                 return -E_AFT_SYNTAX;
1170                         }
1171                 }
1172                 return -E_AFT_SYNTAX;
1173         }
1174         opts.flags = flags;
1175         opts.sorting = sort;
1176         opts.mode = mode;
1177         opts.num_patterns = argc - i;
1178         ret = send_option_arg_callback_request(&query, opts.num_patterns,
1179                 argv + i, com_ls_callback, &ls_output);
1180         if (ret > 0) {
1181                 ret = send_buffer(fd, (char *)ls_output.data);
1182                 free(ls_output.data);
1183         }
1184         return ret;
1185 }
1186
1187 /**
1188  * Call the given function for each file in the audio file table.
1189  *
1190  * \param private_data An arbitrary data pointer, passed to \a func.
1191  * \param func The custom function to be called.
1192  *
1193  * \return The return value of the underlying call to osl_rbtree_loop().
1194  */
1195 int audio_file_loop(void *private_data, osl_rbtree_loop_func *func)
1196 {
1197         return osl_rbtree_loop(audio_file_table, AFTCOL_HASH, private_data,
1198                 func);
1199 }
1200
1201 static struct osl_row *find_hash_sister(HASH_TYPE *hash)
1202 {
1203         const struct osl_object obj = {.data = hash, .size = HASH_SIZE};
1204         struct osl_row *row;
1205
1206         osl_get_row(audio_file_table, AFTCOL_HASH, &obj, &row);
1207         return row;
1208 }
1209
1210 enum aft_row_offsets {
1211         AFTROW_AFHI_OFFSET_POS = 0,
1212         AFTROW_CHUNKS_OFFSET_POS = 2,
1213         AFTROW_AUDIO_FORMAT_OFFSET = 4,
1214         AFTROW_FLAGS_OFFSET = 5,
1215         AFTROW_HASH_OFFSET = 9,
1216         AFTROW_PATH_OFFSET = (AFTROW_HASH_OFFSET + HASH_SIZE),
1217 };
1218
1219 /* never save the afsi, as the server knows it too. Note that afhi might be NULL.
1220  * In this case, afhi won't be stored in the buffer  */
1221 static void save_audio_file_info(HASH_TYPE *hash, const char *path,
1222                 struct audio_format_info *afhi, uint32_t flags,
1223                 uint8_t audio_format_num, struct osl_object *obj)
1224 {
1225         size_t path_len = strlen(path) + 1;
1226         size_t afhi_size = sizeof_afhi_buf(afhi);
1227         size_t size = AFTROW_PATH_OFFSET + path_len + afhi_size
1228                 + sizeof_chunk_info_buf(afhi);
1229         char *buf = para_malloc(size);
1230         uint16_t pos;
1231
1232         write_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET, audio_format_num);
1233         write_u32(buf + AFTROW_FLAGS_OFFSET, flags);
1234
1235         memcpy(buf + AFTROW_HASH_OFFSET, hash, HASH_SIZE);
1236         strcpy(buf + AFTROW_PATH_OFFSET, path);
1237
1238         pos = AFTROW_PATH_OFFSET + path_len;
1239         PARA_DEBUG_LOG("size: %zu, afhi starts at %d\n", size, pos);
1240         PARA_DEBUG_LOG("last afhi byte: %p, pos %zu\n", buf + pos + afhi_size - 1,
1241                 pos + afhi_size - 1);
1242         write_u16(buf + AFTROW_AFHI_OFFSET_POS, pos);
1243         save_afhi(afhi, buf + pos);
1244
1245         pos += afhi_size;
1246         PARA_DEBUG_LOG("size: %zu, chunks start at %d\n", size, pos);
1247         write_u16(buf + AFTROW_CHUNKS_OFFSET_POS, pos);
1248         save_chunk_info(afhi, buf + pos);
1249         PARA_DEBUG_LOG("last byte in buf: %p\n", buf + size - 1);
1250         obj->data = buf;
1251         obj->size = size;
1252 }
1253
1254 /*
1255 input:
1256 ~~~~~~
1257 HS:     hash sister
1258 PB:     path brother
1259 F:      force flag given
1260
1261 output:
1262 ~~~~~~~
1263 AFHI:   whether afhi and chunk table are computed and sent
1264 ACTION: table modifications to be performed
1265
1266 +---+----+-----+------+---------------------------------------------------+
1267 | HS | PB | F  | AFHI | ACTION
1268 +---+----+-----+------+---------------------------------------------------+
1269 | Y |  Y |  Y  |  Y   | if HS != PB: remove PB. HS: force afhi update,
1270 |                     | update path, keep afsi
1271 +---+----+-----+------+---------------------------------------------------+
1272 | Y |  Y |  N  |  N   | if HS == PB: do not send callback request at all.
1273 |                     | otherwise: remove PB, HS: update path, keep afhi,
1274 |                     | afsi.
1275 +---+----+-----+------+---------------------------------------------------+
1276 | Y |  N |  Y  |  Y   | (rename) force afhi update of HS, update path of
1277 |                     | HS, keep afsi
1278 +---+----+-----+------+---------------------------------------------------+
1279 | Y |  N |  N  |  N   | (file rename) update path of HS, keep afsi, afhi
1280 +---+----+-----+------+---------------------------------------------------+
1281 | N |  Y |  Y  |  Y   | (file change) update afhi, hash, of PB, keep afsi
1282 |                     | (force has no effect)
1283 +---+----+-----+------+---------------------------------------------------+
1284 | N |  Y |  N  |  Y   | (file change) update afhi, hash of PB, keep afsi
1285 +---+----+-----+------+---------------------------------------------------+
1286 | N |  N |  Y  |  Y   | (new file) create new entry (force has no effect)
1287 +---+----+-----+------+---------------------------------------------------+
1288 | N |  N |  N  |  Y   | (new file) create new entry
1289 +---+----+-----+------+---------------------------------------------------+
1290
1291 afhi <=> force or no HS
1292
1293 */
1294
1295
1296 #define ADD_FLAG_LAZY 1
1297 #define ADD_FLAG_FORCE 2
1298 #define ADD_FLAG_VERBOSE 4
1299
1300 /* TODO: change log messages so that they get written to the result buffer */
1301
1302 static int com_add_callback(const struct osl_object *query,
1303                 __a_unused struct osl_object *result)
1304 {
1305         char *buf = query->data, *path;
1306         struct osl_row *pb, *aft_row;
1307         const struct osl_row *hs;
1308         struct osl_object objs[NUM_AFT_COLUMNS];
1309         HASH_TYPE *hash;
1310         char asc[2 * HASH_SIZE + 1];
1311         int ret;
1312         char afsi_buf[AFSI_SIZE];
1313         uint32_t flags = read_u32(buf + AFTROW_FLAGS_OFFSET);
1314         struct afs_info default_afsi = {.last_played = 0};
1315
1316         hash = (HASH_TYPE *)buf + AFTROW_HASH_OFFSET;
1317         hash_to_asc(hash, asc);;
1318         objs[AFTCOL_HASH].data = buf + AFTROW_HASH_OFFSET;
1319         objs[AFTCOL_HASH].size = HASH_SIZE;
1320
1321         path = buf + AFTROW_PATH_OFFSET;
1322         objs[AFTCOL_PATH].data = path;
1323         objs[AFTCOL_PATH].size = strlen(path) + 1;
1324
1325         PARA_INFO_LOG("request to add %s\n", path);
1326         hs = find_hash_sister(hash);
1327         ret = aft_get_row_of_path(path, &pb);
1328         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1329                 return ret;
1330         if (hs && pb && hs == pb && !(flags & ADD_FLAG_FORCE)) {
1331                 if (flags & ADD_FLAG_VERBOSE)
1332                         PARA_NOTICE_LOG("ignoring duplicate %p\n", path);
1333                 return 1;
1334         }
1335         if (hs && hs != pb) {
1336                 struct osl_object obj;
1337                 if (pb) { /* hs trumps pb, remove pb */
1338                         if (flags & ADD_FLAG_VERBOSE)
1339                                 PARA_NOTICE_LOG("removing path brother\n");
1340                         ret = osl_del_row(audio_file_table, pb);
1341                         if (ret < 0)
1342                                 return ret;
1343                         pb = NULL;
1344                 }
1345                 /* file rename, update hs' path */
1346                 ret = osl_get_object(audio_file_table, hs, AFTCOL_PATH, &obj);
1347                 if (flags & ADD_FLAG_VERBOSE)
1348                         PARA_NOTICE_LOG("rename %s -> %s\n", (char *)obj.data, path);
1349                 ret = osl_update_object(audio_file_table, hs, AFTCOL_PATH,
1350                         &objs[AFTCOL_PATH]);
1351                 if (ret < 0)
1352                         return ret;
1353                 if (!(flags & ADD_FLAG_FORCE))
1354                         return ret;
1355         }
1356         /* no hs or force mode, child must have sent afhi */
1357         uint16_t afhi_offset = read_u16(buf + AFTROW_AFHI_OFFSET_POS);
1358         uint16_t chunks_offset = read_u16(buf + AFTROW_CHUNKS_OFFSET_POS);
1359
1360         objs[AFTCOL_AFHI].data = buf + afhi_offset;
1361         objs[AFTCOL_AFHI].size = chunks_offset - afhi_offset;
1362         if (!objs[AFTCOL_AFHI].size) /* "impossible" */
1363                 return -E_NO_AFHI;
1364         objs[AFTCOL_CHUNKS].data = buf + chunks_offset;
1365         objs[AFTCOL_CHUNKS].size = query->size - chunks_offset;
1366         if (pb && !hs) { /* update pb's hash */
1367                 char old_asc[2 * HASH_SIZE + 1];
1368                 HASH_TYPE *old_hash;
1369                 ret = get_hash_of_row(pb, &old_hash);
1370                 if (ret < 0)
1371                         return ret;
1372                 hash_to_asc(old_hash, old_asc);
1373                 if (flags & ADD_FLAG_VERBOSE)
1374                         PARA_NOTICE_LOG("file change: %s %s -> %s\n", path,
1375                                 old_asc, asc);
1376                 ret = osl_update_object(audio_file_table, pb, AFTCOL_HASH,
1377                         &objs[AFTCOL_HASH]);
1378                 if (ret < 0)
1379                         return ret;
1380         }
1381         if (hs || pb) { /* (hs != NULL and pb != NULL) implies hs == pb */
1382                 const struct osl_row *row = pb? pb : hs;
1383                 /* update afhi and chunk_table */
1384                 if (flags & ADD_FLAG_VERBOSE)
1385                         PARA_DEBUG_LOG("updating audio format handler info (%zd bytes)\n",
1386                                 objs[AFTCOL_AFHI].size);
1387                 ret = osl_update_object(audio_file_table, row, AFTCOL_AFHI,
1388                         &objs[AFTCOL_AFHI]);
1389                 if (ret < 0)
1390                         return ret;
1391                 if (flags & ADD_FLAG_VERBOSE)
1392                         PARA_DEBUG_LOG("updating chunk table\n");
1393                 ret = osl_update_object(audio_file_table, row, AFTCOL_CHUNKS,
1394                         &objs[AFTCOL_CHUNKS]);
1395                 if (ret < 0)
1396                         return ret;
1397                 return mood_update_audio_file(row, NULL);
1398         }
1399         /* new entry, use default afsi */
1400         default_afsi.last_played = time(NULL) - 365 * 24 * 60 * 60;
1401         default_afsi.audio_format_id = read_u8(buf + AFTROW_AUDIO_FORMAT_OFFSET);
1402
1403         objs[AFTCOL_AFSI].data = &afsi_buf;
1404         objs[AFTCOL_AFSI].size = AFSI_SIZE;
1405         save_afsi(&default_afsi, &objs[AFTCOL_AFSI]);
1406         ret = osl_add_and_get_row(audio_file_table, objs, &aft_row);
1407         if (ret < 0)
1408                 return ret;
1409         return mood_update_audio_file(aft_row, NULL);
1410 }
1411
1412 struct private_add_data {
1413         int fd;
1414         uint32_t flags;
1415 };
1416
1417 static int path_brother_callback(const struct osl_object *query,
1418                 struct osl_object *result)
1419 {
1420         char *path = query->data;
1421         struct osl_row *path_brother;
1422         int ret = aft_get_row_of_path(path, &path_brother);
1423         if (ret < 0)
1424                 return ret;
1425         result->data = para_malloc(sizeof(path_brother));
1426         result->size = sizeof(path_brother);
1427         *(struct osl_row **)(result->data) = path_brother;
1428         return 1;
1429 }
1430
1431 static int hash_sister_callback(const struct osl_object *query,
1432                 struct osl_object *result)
1433 {
1434         HASH_TYPE *hash = query->data;
1435         struct osl_row *hash_sister;
1436
1437         hash_sister = find_hash_sister(hash);
1438         if (!hash_sister)
1439                 return -E_RB_KEY_NOT_FOUND;
1440         result->data = para_malloc(sizeof(hash_sister));
1441         result->size = sizeof(hash_sister);
1442         *(struct osl_row **)(result->data) = hash_sister;
1443         return 1;
1444 }
1445
1446 static int add_one_audio_file(const char *arg, const void *private_data)
1447 {
1448         int ret;
1449         uint8_t format_num = -1;
1450         const struct private_add_data *pad = private_data;
1451         struct audio_format_info afhi, *afhi_ptr = NULL;
1452         struct osl_row *pb = NULL, *hs = NULL; /* path brother/hash sister */
1453         struct osl_object map, obj = {.data = NULL}, query, result;
1454         char *path = NULL;
1455         HASH_TYPE hash[HASH_SIZE];
1456
1457         afhi.header_offset = 0;
1458         afhi.header_len = 0;
1459         ret = verify_path(arg, &path);
1460         if (ret < 0)
1461                 goto out_free;
1462         query.data = path;
1463         query.size = strlen(path) + 1;
1464         ret = send_callback_request(path_brother_callback, &query, &result);
1465         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1466                 goto out_free;
1467         if (ret >= 0) {
1468                 pb = *(struct osl_row **)result.data;
1469                 free(result.data);
1470         }
1471         ret = 1;
1472         if (pb && (pad->flags & ADD_FLAG_LAZY)) { /* lazy is really cheap */
1473                 if (pad->flags & ADD_FLAG_VERBOSE)
1474                         ret = send_va_buffer(pad->fd, "lazy-ignore: %s\n", path);
1475                 goto out_free;
1476         }
1477         /* We still want to add this file. Compute its hash. */
1478         ret = mmap_full_file(path, O_RDONLY, &map);
1479         if (ret < 0)
1480                 goto out_free;
1481         hash_function(map.data, map.size, hash);
1482
1483         /* Check whether database contains file with the same hash. */
1484         query.data = hash;
1485         query.size = HASH_SIZE;
1486         ret = send_callback_request(hash_sister_callback, &query, &result);
1487         if (ret < 0 && ret != -E_RB_KEY_NOT_FOUND)
1488                 goto out_free;
1489         if (ret >= 0) {
1490                 hs = *(struct osl_row **)result.data;
1491                 free(result.data);
1492         }
1493         /* Return success if we already know this file. */
1494         ret = 1;
1495         if (pb && hs && hs == pb && (!(pad->flags & ADD_FLAG_FORCE))) {
1496                 if (pad->flags & ADD_FLAG_VERBOSE)
1497                         ret = send_va_buffer(pad->fd,
1498                                 "not forcing update: %s\n", path);
1499                 goto out_unmap;
1500         }
1501         /*
1502          * we won't recalculate the audio format info and the chunk table if
1503          * there is a hash sister unless in FORCE mode.
1504          */
1505         if (!hs || (pad->flags & ADD_FLAG_FORCE)) {
1506                 ret = compute_afhi(path, map.data, map.size, &afhi);
1507                 if (ret < 0)
1508                         goto out_unmap;
1509                 format_num = ret;
1510                 afhi_ptr = &afhi;
1511         }
1512         if (pad->flags & ADD_FLAG_VERBOSE)
1513                 send_va_buffer(pad->fd, "adding %s\n", path);
1514         munmap(map.data, map.size);
1515         save_audio_file_info(hash, path, afhi_ptr, pad->flags, format_num, &obj);
1516         /* Ask afs to consider this entry for adding. */
1517         ret = send_callback_request(com_add_callback, &obj, NULL);
1518         goto out_free;
1519
1520 out_unmap:
1521         munmap(map.data, map.size);
1522 out_free:
1523         if (ret < 0)
1524                 send_va_buffer(pad->fd, "failed to add %s (%s)\n", path?
1525                         path : arg, PARA_STRERROR(-ret));
1526         free(obj.data);
1527         free(path);
1528         if (afhi_ptr)
1529                 free(afhi_ptr->chunk_table);
1530         return 1; /* it's not an error if not all files could be added */
1531 }
1532
1533 int com_add(int fd, int argc, char * const * const argv)
1534 {
1535         int i, ret;
1536         struct private_add_data pad = {.fd = fd, .flags = 0};
1537         struct stat statbuf;
1538
1539         for (i = 1; i < argc; i++) {
1540                 const char *arg = argv[i];
1541                 if (arg[0] != '-')
1542                         break;
1543                 if (!strcmp(arg, "--")) {
1544                         i++;
1545                         break;
1546                 }
1547                 if (!strcmp(arg, "-l")) {
1548                         pad.flags |= ADD_FLAG_LAZY;
1549                         continue;
1550                 }
1551                 if (!strcmp(arg, "-f")) {
1552                         pad.flags |= ADD_FLAG_FORCE;
1553                         continue;
1554                 }
1555                 if (!strcmp(arg, "-v")) {
1556                         pad.flags |= ADD_FLAG_VERBOSE;
1557                         continue;
1558                 }
1559         }
1560         if (argc <= i)
1561                 return -E_AFT_SYNTAX;
1562         for (; i < argc; i++) {
1563                 char *path = para_strdup(argv[i]);
1564                 size_t len = strlen(path);
1565                 while (len > 1 && path[--len] == '/')
1566                         path[len] = '\0';
1567                 ret = stat(path, &statbuf);
1568                 if (ret < 0)
1569                         PARA_NOTICE_LOG("failed to stat %s (%s)", path,
1570                                 strerror(errno));
1571                 else
1572                         if (S_ISDIR(statbuf.st_mode))
1573                                 for_each_file_in_dir(path, add_one_audio_file,
1574                                         &pad);
1575                         else
1576                                 add_one_audio_file(path, &pad);
1577                 free(path);
1578         }
1579         ret = 1;
1580         return ret;
1581
1582 }
1583
1584 struct com_touch_options {
1585         long num_played;
1586         long last_played;
1587         long lyrics_id;
1588         long image_id;
1589 };
1590
1591 static int com_touch_callback(const struct osl_object *query,
1592                 __a_unused struct osl_object *result)
1593 {
1594         struct com_touch_options *cto = query->data;
1595         char *p = (char *)query->data + sizeof(*cto);
1596         size_t len;
1597         int ret, no_options = cto->num_played < 0 && cto->last_played < 0 &&
1598                 cto->lyrics_id < 0 && cto->image_id < 0;
1599
1600         for (;p < (char *)query->data + query->size; p += len + 1) {
1601                 struct afs_info old_afsi, new_afsi;
1602                 struct osl_object obj;
1603                 struct osl_row *row;
1604
1605                 len = strlen(p);
1606                 ret = aft_get_row_of_path(p, &row);
1607                 if (ret < 0)
1608                         return ret;
1609                 ret = get_afsi_object_of_row(row, &obj);
1610                 if (ret < 0)
1611                         return ret;
1612                 ret = load_afsi(&old_afsi, &obj);
1613                 if (ret < 0)
1614                         return ret;
1615                 new_afsi = old_afsi;
1616                 if (no_options) {
1617                         new_afsi.num_played++;
1618                         new_afsi.last_played = time(NULL);
1619                 } else {
1620                         if (cto->lyrics_id >= 0)
1621                                 new_afsi.lyrics_id = cto->lyrics_id;
1622                         if (cto->image_id >= 0)
1623                                 new_afsi.image_id = cto->image_id;
1624                         if (cto->num_played >= 0)
1625                                 new_afsi.num_played = cto->num_played;
1626                         if (cto->last_played >= 0)
1627                                 new_afsi.last_played = cto->last_played;
1628                 }
1629                 save_afsi(&new_afsi, &obj); /* in-place update */
1630                 ret = mood_update_audio_file(row, &old_afsi);
1631                 if (ret < 0)
1632                         return ret;
1633         }
1634         return 1;
1635 }
1636
1637 int com_touch(__a_unused int fd, int argc, char * const * const argv)
1638 {
1639         struct com_touch_options cto = {
1640                 .num_played = -1,
1641                 .last_played = -1,
1642                 .lyrics_id = -1,
1643                 .image_id = -1
1644         };
1645         struct osl_object options = {.data = &cto, .size = sizeof(cto)};
1646         int i, ret;
1647
1648
1649         for (i = 1; i < argc; i++) {
1650                 const char *arg = argv[i];
1651                 if (arg[0] != '-')
1652                         break;
1653                 if (!strcmp(arg, "--")) {
1654                         i++;
1655                         break;
1656                 }
1657                 if (!strncmp(arg, "-n", 2)) {
1658                         ret = para_atol(arg + 2, &cto.num_played);
1659                         if (ret < 0)
1660                                 goto err;
1661                         continue;
1662                 }
1663                 if (!strncmp(arg, "-l", 2)) {
1664                         ret = para_atol(arg + 2, &cto.last_played);
1665                         if (ret < 0)
1666                                 goto err;
1667                         continue;
1668                 }
1669                 if (!strncmp(arg, "-y", 2)) {
1670                         ret = para_atol(arg + 2, &cto.lyrics_id);
1671                         if (ret < 0)
1672                                 goto err;
1673                         continue;
1674                 }
1675                 if (!strncmp(arg, "-i", 2)) {
1676                         ret = para_atol(arg + 2, &cto.image_id);
1677                         if (ret < 0)
1678                                 goto err;
1679                         continue;
1680                 }
1681         }
1682         ret = -E_AFT_SYNTAX;
1683         if (i >= argc)
1684                 goto err;
1685         return send_option_arg_callback_request(&options, argc - i,
1686                 argv + i, com_touch_callback, NULL);
1687 err:
1688         return ret;
1689 }
1690
1691 struct com_rm_options {
1692         uint32_t flags;
1693 };
1694
1695 static int com_rm_callback(const struct osl_object *query,
1696                 __a_unused struct osl_object *result)
1697 {
1698         struct com_rm_options *cro = query->data;
1699         char *p = (char *)query->data + sizeof(*cro);
1700         size_t len;
1701         int ret;
1702
1703         for (;p < (char *)query->data + query->size; p += len + 1) {
1704                 struct osl_row *row;
1705
1706                 len = strlen(p);
1707                 ret = aft_get_row_of_path(p, &row);
1708                 if (ret < 0)
1709                         return ret;
1710                 ret = mood_delete_audio_file(row);
1711                 if (ret < 0)
1712                         return ret;
1713                 ret = osl_del_row(audio_file_table, row);
1714                 if (ret < 0)
1715                         return ret;
1716         }
1717         return 1;
1718 }
1719
1720 /*
1721  * TODO options: -v verbose, -f dont stop if file not found
1722  * -h remove by hash, use fnmatch
1723  *
1724  * */
1725
1726 int com_afs_rm(__a_unused int fd, int argc,  char * const * const argv)
1727 {
1728         struct com_rm_options cro = {.flags = 0};
1729         struct osl_object options = {.data = &cro, .size = sizeof(cro)};
1730         int i, ret;
1731
1732         for (i = 1; i < argc; i++) {
1733                 const char *arg = argv[i];
1734                 if (arg[0] != '-')
1735                         break;
1736                 if (!strcmp(arg, "--")) {
1737                         i++;
1738                         break;
1739                 }
1740         }
1741         ret = -E_AFT_SYNTAX;
1742         if (i >= argc)
1743                 goto err;
1744         return send_option_arg_callback_request(&options, argc - i,
1745                 argv + i, com_rm_callback, NULL);
1746 err:
1747         return ret;
1748 }
1749
1750 /* TODO: optionally fix problems by removing offending rows */
1751 static int check_audio_file(struct osl_row *row, void *data)
1752 {
1753         char *path;
1754         struct para_buffer *pb = data;
1755         struct stat statbuf;
1756         int ret = get_audio_file_path_of_row(row, &path);
1757         struct afs_info afsi;
1758         char *blob_name;
1759
1760         if (ret < 0) {
1761                 para_printf(pb, "%s\n", PARA_STRERROR(-ret));
1762                 return 1;
1763         }
1764         if (stat(path, &statbuf) < 0)
1765                 para_printf(pb, "%s: stat error (%s)\n", path, strerror(errno));
1766         else {
1767                 if (!S_ISREG(statbuf.st_mode))
1768                         para_printf(pb, "%s: not a regular file\n", path);
1769         }
1770         ret = get_afsi_of_row(row, &afsi);
1771         if (ret < 0) {
1772                 para_printf(pb, "%s: %s\n", path, PARA_STRERROR(-ret));
1773                 return 1;
1774         }
1775         ret = lyr_get_name_by_id(afsi.lyrics_id, &blob_name);
1776         if (ret < 0)
1777                 para_printf(pb, "%s lyrics id %u: %s\n", path, afsi.lyrics_id,
1778                         PARA_STRERROR(-ret));
1779         ret = img_get_name_by_id(afsi.image_id, &blob_name);
1780         if (ret < 0)
1781                 para_printf(pb, "%s image id %u: %s\n", path, afsi.image_id,
1782                         PARA_STRERROR(-ret));
1783         return 1;
1784 }
1785
1786 int aft_check_callback(__a_unused const struct osl_object *query, struct osl_object *result)
1787 {
1788         struct para_buffer pb = {.buf = NULL};
1789
1790         para_printf(&pb, "checking audio file table...\n");
1791         audio_file_loop(&pb, check_audio_file);
1792         result->data = pb.buf;
1793         result->size = pb.size;
1794         return 1;
1795
1796 }
1797
1798 /**
1799  * Close the audio file table.
1800  *
1801  * \param flags Ususal flags that are passed to osl_close_table().
1802  *
1803  * \sa osl_close_table().
1804  */
1805 void aft_shutdown(enum osl_close_flags flags)
1806 {
1807         osl_close_table(audio_file_table, flags);
1808         audio_file_table = NULL;
1809 }
1810
1811 /**
1812  * Open the audio file table.
1813  *
1814  * \param ti Gets initialized by this function.
1815  * \param db The database directory.
1816  *
1817  * \return Positive on success, negative on errors.
1818  *
1819  * \sa osl_open_table().
1820  */
1821 int aft_init(struct table_info *ti, const char *db)
1822 {
1823         int ret;
1824
1825         audio_file_table_desc.dir = db;
1826         ti->desc = &audio_file_table_desc;
1827         ret = osl_open_table(ti->desc, &ti->table);
1828         if (ret >= 0) {
1829                 unsigned num;
1830                 audio_file_table = ti->table;
1831                 osl_get_num_rows(audio_file_table, &num);
1832                 PARA_INFO_LOG("audio file table contains %d files\n", num);
1833                 return ret;
1834         }
1835         PARA_INFO_LOG("failed to open audio file table\n");
1836         audio_file_table = NULL;
1837         return ret == -E_NOENT? 1 : ret;
1838 }