# -*- coding: utf-8 -*-
__author__ = 'manman'

import json
import urllib.request

"""
读取1.json文件内容，然后解析出来把mp3下载地址找到，然后下载mp3文件。

"""

# import os
#
# for r, ds, fs in os.walk("/home/test"):
#     for f in fs:
#         fn = os.path.join(r, f)
#         if f == "A":
#             print(os.path.abspath(fn))
#
#
# def file_hdl(name='1.json'):
#     f = open(name)
#     for line in f:
#         print(line)


def read_content(filename):
    """
    从filename读取数据
    :param filename:
    :return:
    """
    result = ''
    f = open(filename)
    for line in f:
        result += line
    f.close()
    return result


def find_mp3_link(content):
    """
    从content里面找到mp3链接
    :param content:
    :return:
    """
    json_data = json.loads(content)
    print(json_data)
    res = []
    for item in json_data:
        res.append(item['mp3'])
    return res  # http://luoo-mp3.kssws.ks-cdn.com/low/luoo/radio1/1.mp3


def store_mp3(mp3_links):
    """
    根据mp3链接下载mp3文件，然后存储到本地
    :param mp3_link:
    :return:
    """
    for link in mp3_links:
        res = urllib.request.urlopen(link).read()
        f = open(link.split('/')[-1], 'wb')
        f.write(res)
        f.close()
        print('{mp3} download success.'.format(mp3=link.split('/')[-1]))


if __name__ == '__main__':
    content = read_content('1.json')
    mp3_links = find_mp3_link(content)
    store_mp3(mp3_links)
