Completed
Push — master ( d3716d...db9ca9 )
by Sepand
47s
created

create_folder()   B

Complexity

Conditions 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 4 Features 1
Metric Value
cc 5
c 5
b 4
f 1
dl 0
loc 16
rs 8.5454
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
import time
10
import sys
11
import urllib.request
12
meta_input=""
13
def read_lorem(char=100):
14
    try:
15
        lorem_file=open("Latin-Lipsum.txt","r")
16
        lorem_text=lorem_file.read()
17
        lorem_file.close()
18
        return lorem_text
19
    except:
20
        return None
21
def sample_site_download():
22
    try:
23
        if internet():
24
            print("Downloading . . . ")
25
            urllib.request.urlretrieve("http://www.qpage.ir/sample/profile.png",os.path.join(image_dir,"profile.png"))
26
            urllib.request.urlretrieve("http://www.qpage.ir/sample/font.TTF", os.path.join(font_dir, "font.TTF"))
27
            urllib.request.urlretrieve("http://www.qpage.ir/sample/resume.pdf", os.path.join(doc_dir, "resume.pdf"))
28
            urllib.request.urlretrieve("http://www.qpage.ir/sample/resume.txt", os.path.join(doc_dir, "resume.txt"))
29
            urllib.request.urlretrieve("http://www.qpage.ir/sample/icon.ico", os.path.join(image_dir, "icon.ico"))
30
            print("Done!")
31
            print_line(70)
32
        else:
33
            print("Error In Internet Connection!")
34
            print_line(70)
35
    except:
36
        print("Error In Download Sample")
37
        print_line(70)
38
def logger(status=False):
39
    file=open("build_log.txt","a")
40
    if status==False:
41
        file.write("Faild  "+str(datetime.datetime.now())+"\n")
42
    else:
43
        file.write("Sucess "+str(datetime.datetime.now())+"\n")
44
    file.close()
45
46
47
def print_line(number,char="-"):
48
    line=""
49
    for i in range(number):
50
        line=line+char
51
    print(line)
52
53
def name_standard(name):
54
    reponse_name=name[0].upper()+name[1:].lower()
55
    return reponse_name
56
def address_print():
57
    print_line(70,"*")
58
    print("Where--> "+work_dir)
59
    print_line(70, "*")
60
def create_folder():  # This Function Create Empty Folder At Begin
61
    folder_flag = 0
62
    list_of_folders = os.listdir(work_dir)
63
    for i in ["doc","image","output","font"]:
64
        if i not in list_of_folders:
65
            os.mkdir(i)
66
            folder_flag += 1
67
            if i=="doc":
68
                file = open(os.path.join(doc_dir, "index.txt"), "w")
69
                index_contain=read_lorem()
70
                if index_contain==None:
71
                    file.write("This is For First Page . . .")
72
                else:
73
                    file.write(index_contain)
74
                file.close()
75
    return bool(folder_flag)
76
77
78
def page_name_update():  # This Function Update Page Names
79
    for i in os.listdir(doc_dir):
80
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
81
            actual_name.append(i[:-4])
82
            page_name.append(i[:-4])
83
84
85
def menu_maker():  # Top Menu Maker In each html page
86
    result = "<center>"
87
    for i in range(len(page_name)):
88
        if page_name[i] == "Home":
89
            targets_blank = ""
90
        else:
91
            targets_blank = 'target="blank"'
92
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + name_standard(page_name[
93
            i]) + "</a>\n"  # Hyper Link To Each Page In HTML File
94
        result += "&nbsp\n"
95
    result += "</center>"
96
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
97
    return result  # Return All Of The Menu
98
99
100
def menu_writer():  # Write menu_maker output in html file
101
    message = menu_maker()
102
    for i in range(len(page_name)):
103
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
104
        file.write(message)
105
        file.close()
106
107
108
def print_meta():
109
    global meta_input
110
    meta_input = input("Please Enter Your Name : ")
111
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
112
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
113
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
114
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
115
    if len(meta_input) < 4:
116
        warnings.append("[Warning] Your input for name is too short!!")
117
    return static_meta
118
119
120
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
121
    html_name = os.path.join(out_dir, name + ".html")
122
    file = open(html_name, "w")
123
    file.write("<html>\n")
124
    file.write("\t<head>\n")
125
    if name == "index":
126
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
127
    else:
128
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
129
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
130
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
131
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
132
133
    if name == 'index':  # Add meta only for index page
134
        file.write(print_meta())
135
136
    file.write("\t</head>\n")
137
    file.write('\t<body class="body_tag">\n')
138
    file.close()
139
140
141
def html_end(name):  # Create End Of The Html file
142
    html_name = os.path.join(out_dir, name + ".html")
143
    file = open(html_name, "a")
144
    file.write("\t</body>\n")
145
    file.write("</html>")
146
    file.close()
147
148
149
def close_files():
150
    for i in files:
151
        i.close()
152
153
def LSM_translate(line,center):
154
    line.strip()
155
    text = line
156
    header_start = '<h4 class="color_tag">'
157
    header_end = "</h4>"
158
    if line.find("[L]") != -1:
159
        header_start = '<h2 class="color_tag">'
160
        header_end = "</h2>"
161
        text = line[3:]
162
    elif line.find("[S]") != -1:
163
        header_start = '<h5 class="color_tag">'
164
        header_end = "</h5>"
165
        text = line[3:]
166
    elif line.find("[M]") != -1:
167
        text = line[3:]
168
    if center:  # Centerizes Text If Condition Is True For Manual Centering
169
        header_start = "<center>" + header_start
170
        header_end += "</center>"
171
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
172
        header_start = "<center>" + header_start
173
        header_end += "</center>"
174
        text = text[:text.find("[center]")]
175
    return [text,header_end,header_start]
176
177
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
178
    text_code=""
179
    for line in text_file:
180
        if len(line)==1:
181
            text_code = space
182
        else:
183
            text_header=LSM_translate(line,center)
184
            text=text_header[0]
185
            header_end =text_header[1]
186
            header_start =text_header[2]
187
            text_code = header_start + text + header_end + "\n"
188
        file.write(text_code)
189
    if close:
190
        file.close()
191
192
193
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
194
    for i in range(len(size_box)):
195
        print(i, "-", size_box[i])
196
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
197
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
198
    if 0 <= image_size < len(size_box):
199
        image_size_string = size_box[image_size]
200
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + '></img></center>\n'
201
    file.write(image_code)
202
    if close:
203
        file.close()
204
205
206
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
207
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
208
    if center:
209
        link_code = "<center>" + link_code + "</center>"
210
    file.write(link_code + "\n")
211
    file.write(break_line)
212
    if close:
213
        file.close()
214
215
216
def print_adv(file, close=True):
217
    file.write(break_line)
218
    file.write(
219
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
220
    if close:
221
        file.close()
222
223
224
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
225
    file = open(os.path.join(out_dir, name + ".html"), "a")
226
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
227
    files.append(file)
228
    files.append(text_file)
229
    resume_name = ""
230
    image_name = ""
231
    imformat = "jpg"
232
    if name.upper() == "INDEX":
233
        file_of_images = os.listdir(image_dir)
234
        for i in range(len(file_of_images)):
235
            for form in imformat_box:
236
                if file_of_images[i].find("." + form) != -1:
237
                    image_name = os.path.join(image_dir, file_of_images[i])
238
                    imformat = form
239
                    global image_counter
240
                    image_counter=1
241
                    break
242
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
243
        print_image(file, imformat=imformat)
244
        print_text(text_file, file)
245
        print_adv(file)
246
    elif name.upper() == "RESUME":
247
        file_of_docs = os.listdir(doc_dir)
248
        for i in range(len(file_of_docs)):
249
            if file_of_docs[i].find(".pdf") != -1:
250
                resume_name = os.path.join(doc_dir, file_of_docs[i])
251
                global pdf_counter
252
                pdf_counter=1
253
                break
254
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
255
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
256
        print_text(text_file, file)
257
        # print_adv(file)
258
    else:
259
        print_text(text_file, file)
260
        # print_adv(file)
261
262
263
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
264
    if os.path.exists(path):
265
        list_of_files = os.listdir(path)
266
        for file in list_of_files:
267
            os.remove(os.path.join(path, file))
268
    else:
269
        os.mkdir(path)
270
271
272
def print_warning():
273
    print(str(len(warnings)) + " Warning , 0 Error")
274
    for i in range(len(warnings)):
275
        print(str(i + 1) + "-" + warnings[i])
276
277
278
def get_color_code():
279
    for i in range(len(color_box)):
280
        print(i, "-", color_box[i])
281
    back_color_code = int(input("Please enter your background color : "))
282
    if back_color_code not in range(7):
283
        back_color_code = 0
284
    text_color_code = int(input("Please enter your text color : "))
285
    if text_color_code not in range(7):
286
        text_color_code = 1
287
    return [back_color_code,text_color_code]
288
289
def color_code_map():
290
    [back_color_code, text_color_code]=get_color_code()
291
    if text_color_code == back_color_code:
292
        warnings.append("[Warning] Your text color and background color are same!!")
293
    background_color = color_box[back_color_code]  # convert code to color string in color_box
294
    text_color = color_box[text_color_code]  # convert code to color string in color_box
295
    return [background_color,text_color]
296
297
def css_font(font_folder):
298
    font_flag = 0  # 0 If there is no font file in font_folder
299
    current_font_format=None
300
    for i in font_folder:
301
        for j in range(len(font_format)):  # search for other font format in font box
302
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
303
                shutil.copyfile(os.path.join(font_dir, i),
304
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
305
                font_flag = 1  # Turn Flag On
306
                current_font_format = font_format[j]  # font format of current selected font for css editing
307
    return [font_flag,current_font_format]
308
def css_creator():  # Ask For background and text color in
309
    font_section = 'font-family : Georgia , serif;\n'
310
    colors=color_code_map()
311
    background_color=colors[0]
312
    text_color=colors[1]
313
    font_folder = os.listdir(font_dir)
314
    details=css_font(font_folder)
315
    current_font_format=details[1]
316
    font_flag=details[0]
317
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
318
    if font_flag == 1:  # check flag if it is 1
319
        css_file.write(
320
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
321
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
322
        for i in range(len(fontstyle_box)):
323
            print(i, "-", fontstyle_box[i])
324
        font_style = int(input(" Please choose your font style "))
325
        if font_style < len(fontstyle_box):
326
            font_style = fontstyle_box[font_style]
327
        else:
328
            font_style = "normal"
329
        font_section = font_section + "font-style:" + font_style + ";\n"
330
    else:
331
        warnings.append("[Warning] There is no specific font set for this website!!")
332
    css_file.write(
333
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
334
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
335
    css_file.write(css_animation_2)
336
    css_file.close()  # close css file
337
338
339
def preview():
340
    webbrowser.open(os.path.join(out_dir, "index.html"))
341
342
343
def error_finder():
344
    error_vector = []
345
    pass_vector = []
346
    pdf_counter = 0
347
    image_list = os.listdir(image_dir)
348
    doc_list = os.listdir(doc_dir)
349
    if image_counter == 1:
350
        pass_vector.append("[Pass] Your profile image in OK!!")
351
    else:
352
        error_vector.append("[Error] Your profile image is not in correct format")
353
    if len(doc_list) == 0:
354
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
355
    else:
356
        if "index.txt" in doc_list:
357
            pass_vector.append("[Pass] index.txt file OK!")
358
        else:
359
            error_vector.append("[Error] index.txt is not in doc folder!")
360
        if pdf_counter == 0:
361
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
362
        else:
363
            pass_vector.append("[Pass] Your Resume File is OK!!")
364
    return [error_vector, pass_vector]
365
366
367
def icon_creator():
368
    icon_flag=0
369
    for file in os.listdir(image_dir):
370
        if file.endswith('ico'):
371
            shutil.copy(os.path.join(image_dir, file), out_dir)
372
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
373
            icon_flag=1
374
            break
375
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
376
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
377
        warnings.append("[warning] There is no icon for this website")
378
def robot_maker(): # This Function Create Robots.txt for pages
379
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
380
    robots.write("User-agent: *\n")
381
    robots.write("Disallow: ")
382
    robots.close()
383
def internet(host="8.8.8.8", port=53, timeout=3):
384
    try:
385
        socket.setdefaulttimeout(timeout)
386
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
387
        return True
388
    except Exception as ex:
389
        return False
390
def server():
391
    global meta_input
392
    url="http://sepkjaer.pythonanywhere.com/install"
393
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
394
    response=requests.get(url,headers=headers)
395
    #print(response)
396
def version_control():
397
    try:
398
        print("Check for new version . . .")
399
        print_line(70)
400
        version_pattern=r"last_version:(.+)"
401
        if internet():
402
            response=requests.get("http://www.qpage.ir/releases.html")
403
            body=response.text
404
            last_version=float(re.findall(version_pattern,body)[0][:-3])
405
            if last_version>float(version):
406
                print_line(70)
407
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
408
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
409
                print_line(70)
410
            else:
411
                print ("Already Updated!!!")
412
                print_line(70)
413
    except:
414
        pass
415
def enter_to_exit(mode=False):
416
    print_line(70,"*")
417
    response=input("Enter [R] for restart Qpage and any other key to exit : ")
418
    if response.upper()!="R":
419
        sys.exit()
420
421
422
423
def wait_func(iteration):
424
    for i in range(iteration):
425
        time.sleep(1)
426
        print(".")
427
428
429
430