The next generation of the Teknik Services. Written in ASP.NET. Fork for blog tags.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Data.Entity;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Mail;
  9. using System.Reflection;
  10. using System.Text;
  11. using Teknik.Areas.Transparency.Models;
  12. using Teknik.Areas.Upload.Models;
  13. using Teknik.Areas.Users.Models;
  14. using Teknik.Areas.Users.Utility;
  15. using Teknik.Configuration;
  16. using Teknik.Helpers;
  17. using Teknik.Models;
  18. namespace ServerMaint
  19. {
  20. public class Program
  21. {
  22. private static string currentPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
  23. private static string virusFile = Path.Combine(currentPath, "virusLogs.txt");
  24. private static string errorFile = Path.Combine(currentPath, "errorLogs.txt");
  25. private static string configPath = currentPath;
  26. private const string TAKEDOWN_REPORTER = "Teknik Automated System";
  27. public static event Action<string> OutputEvent;
  28. public static int Main(string[] args)
  29. {
  30. try
  31. {
  32. ArgumentOptions options = new ArgumentOptions();
  33. var parser = new CommandLine.Parser(config => config.HelpWriter = Console.Out);
  34. if (parser.ParseArguments(args, options))
  35. {
  36. if (!string.IsNullOrEmpty(options.Config))
  37. configPath = options.Config;
  38. if (Directory.Exists(configPath))
  39. {
  40. Config config = Config.Load(configPath);
  41. TeknikEntities db = new TeknikEntities();
  42. Output(string.Format("[{0}] Started Server Maintenance Process.", DateTime.Now));
  43. // Scan all the uploads for viruses, and remove the bad ones
  44. if (options.ScanUploads && config.UploadConfig.VirusScanEnable)
  45. {
  46. ScanUploads(config, db);
  47. }
  48. // Warns all the invalid accounts via email
  49. if (options.WarnAccounts)
  50. {
  51. WarnInvalidAccounts(config, db);
  52. }
  53. // Cleans all inactive users
  54. if (options.CleanUsers)
  55. {
  56. CleanAccounts(config, db, options.DaysBeforeDeletion);
  57. }
  58. // Cleans the email for unused accounts
  59. if (options.CleanEmails)
  60. {
  61. CleanEmail(config, db);
  62. }
  63. // Cleans all the git accounts that are unused
  64. if (options.CleanGit)
  65. {
  66. CleanGit(config, db);
  67. }
  68. // Generates a file for all of the user's last seen dates
  69. if (options.GenerateLastSeen)
  70. {
  71. GenerateLastSeen(config, db, options.LastSeenFile);
  72. }
  73. // Generates a file for all of the invalid accounts
  74. if (options.GenerateInvalid)
  75. {
  76. GenerateInvalidAccounts(config, db, options.InvalidFile);
  77. }
  78. // Generates a file for all of the accounts to be cleaned
  79. if (options.GenerateCleaning)
  80. {
  81. GenerateCleaningList(config, db, options.CleaningFile, options.DaysBeforeDeletion);
  82. }
  83. Output(string.Format("[{0}] Finished Server Maintenance Process.", DateTime.Now));
  84. return 0;
  85. }
  86. else
  87. {
  88. string msg = string.Format("[{0}] Config File does not exist.", DateTime.Now);
  89. File.AppendAllLines(errorFile, new List<string> { msg });
  90. Output(msg);
  91. }
  92. }
  93. else
  94. {
  95. Output(options.GetUsage());
  96. }
  97. }
  98. catch (Exception ex)
  99. {
  100. string msg = string.Format("[{0}] Exception: {1}", DateTime.Now, ex.GetFullMessage(true));
  101. File.AppendAllLines(errorFile, new List<string> { msg });
  102. Output(msg);
  103. }
  104. return -1;
  105. }
  106. public static void ScanUploads(Config config, TeknikEntities db)
  107. {
  108. Output(string.Format("[{0}] Started Virus Scan.", DateTime.Now));
  109. List<Upload> uploads = db.Uploads.ToList();
  110. // Initialize ClamAV
  111. ClamClient clam = new ClamClient(config.UploadConfig.ClamServer, config.UploadConfig.ClamPort);
  112. clam.MaxStreamSize = config.UploadConfig.MaxUploadSize;
  113. int totalCount = uploads.Count();
  114. int totalScans = 0;
  115. int totalClean = 0;
  116. int totalViruses = 0;
  117. foreach (Upload upload in uploads)
  118. {
  119. totalScans++;
  120. string subDir = upload.FileName[0].ToString();
  121. string filePath = Path.Combine(config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  122. if (File.Exists(filePath))
  123. {
  124. // Read in the file
  125. byte[] data = File.ReadAllBytes(filePath);
  126. // If the IV is set, and Key is set, then decrypt it
  127. if (!string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  128. {
  129. // Decrypt the data
  130. data = AES.Decrypt(data, upload.Key, upload.IV);
  131. }
  132. // We have the data, let's scan it
  133. ClamScanResult scanResult = clam.SendAndScanFile(data);
  134. switch (scanResult.Result)
  135. {
  136. case ClamScanResults.Clean:
  137. totalClean++;
  138. string cleanMsg = string.Format("[{0}] Clean Scan: {1}/{2} Scanned | {3} - {4}", DateTime.Now, totalScans, totalCount, upload.Url, upload.FileName);
  139. Output(cleanMsg);
  140. break;
  141. case ClamScanResults.VirusDetected:
  142. totalViruses++;
  143. string msg = string.Format("[{0}] Virus Detected: {1} - {2} - {3}", DateTime.Now, upload.Url, upload.FileName, scanResult.InfectedFiles.First().VirusName);
  144. File.AppendAllLines(virusFile, new List<string> { msg });
  145. Output(msg);
  146. // Delete from the DB
  147. db.Uploads.Remove(upload);
  148. db.SaveChanges();
  149. // Delete the File
  150. if (File.Exists(filePath))
  151. {
  152. File.Delete(filePath);
  153. }
  154. break;
  155. case ClamScanResults.Error:
  156. string errorMsg = string.Format("[{0}] Scan Error: {1}", DateTime.Now, scanResult.RawResult);
  157. File.AppendAllLines(errorFile, new List<string> { errorMsg });
  158. Output(errorMsg);
  159. break;
  160. case ClamScanResults.Unknown:
  161. string unkMsg = string.Format("[{0}] Unknown Scan Result: {1}", DateTime.Now, scanResult.RawResult);
  162. File.AppendAllLines(errorFile, new List<string> { unkMsg });
  163. Output(unkMsg);
  164. break;
  165. }
  166. }
  167. }
  168. if (totalViruses > 0)
  169. {
  170. // Add to transparency report if any were found
  171. Takedown report = db.Takedowns.Create();
  172. report.Requester = TAKEDOWN_REPORTER;
  173. report.RequesterContact = config.SupportEmail;
  174. report.DateRequested = DateTime.Now;
  175. report.Reason = "Malware Found";
  176. report.ActionTaken = string.Format("{0} Uploads removed", totalViruses);
  177. report.DateActionTaken = DateTime.Now;
  178. db.Takedowns.Add(report);
  179. db.SaveChanges();
  180. }
  181. Output(string.Format("Scanning Complete. {0} Scanned | {1} Viruses Found | {2} Total Files", totalScans, totalViruses, totalCount));
  182. }
  183. public static void WarnInvalidAccounts(Config config, TeknikEntities db)
  184. {
  185. Output(string.Format("[{0}] Started Warning of Invalid Accounts.", DateTime.Now));
  186. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  187. foreach (string account in invalidAccounts)
  188. {
  189. // Let's send them an email :D
  190. string email = UserHelper.GetUserEmailAddress(config, account);
  191. SmtpClient client = new SmtpClient();
  192. client.Host = config.ContactConfig.Host;
  193. client.Port = config.ContactConfig.Port;
  194. client.EnableSsl = config.ContactConfig.SSL;
  195. client.DeliveryMethod = SmtpDeliveryMethod.Network;
  196. client.UseDefaultCredentials = true;
  197. client.Credentials = new NetworkCredential(config.ContactConfig.Username, config.ContactConfig.Password);
  198. client.Timeout = 5000;
  199. try
  200. {
  201. MailMessage mail = new MailMessage(config.SupportEmail, email);
  202. mail.Subject = "Invalid Account Notice";
  203. mail.Body = string.Format(@"
  204. The account {0} does not meet the requirements for a valid username.
  205. The username must meet the following requirements: {1}
  206. It must also be greater than or equal to {2} characters in length, and less than or equal to {3} characters in length.
  207. This email is to let you know that this account will be deleted in {4} days ({5}) in order to comply with the username restrictions. If you would like to keep your data, you should create a new account and transfer the data over to the new account.
  208. In order to make the process as easy as possible, you can reply to this email to ask for your current account to be renamed to another available account. This would keep all your data intact, and just require you to change all references to your email/git/user to the new username. If you wish to do this, please respond within {6} days ({7}) with the new username you would like to use.
  209. Thank you for your continued use of Teknik!
  210. - Teknik Administration", account, config.UserConfig.UsernameFilterLabel, config.UserConfig.MinUsernameLength, config.UserConfig.MaxUsernameLength, 30, DateTime.Now.AddDays(30).ToShortDateString(), 15, DateTime.Now.AddDays(15).ToShortDateString());
  211. mail.BodyEncoding = UTF8Encoding.UTF8;
  212. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
  213. client.Send(mail);
  214. }
  215. catch (Exception ex)
  216. {
  217. Output(string.Format("[{0}] Unable to send email to {1}. Exception: {2}", DateTime.Now, email, ex.Message));
  218. }
  219. }
  220. Output(string.Format("[{0}] Finished Warning of Invalid Accounts. {1} Accounts Warned.", DateTime.Now, invalidAccounts.Count));
  221. }
  222. public static void CleanAccounts(Config config, TeknikEntities db, int maxDays)
  223. {
  224. Output(string.Format("[{0}] Started Cleaning of Inactive/Invalid Users.", DateTime.Now));
  225. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  226. List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
  227. // Delete invalid accounts
  228. foreach (string account in invalidAccounts)
  229. {
  230. UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
  231. }
  232. if (invalidAccounts.Count > 0)
  233. {
  234. // Add to transparency report if any users were removed
  235. Takedown report = db.Takedowns.Create();
  236. report.Requester = TAKEDOWN_REPORTER;
  237. report.RequesterContact = config.SupportEmail;
  238. report.DateRequested = DateTime.Now;
  239. report.Reason = "Username Invalid";
  240. report.ActionTaken = string.Format("{0} Accounts Removed", invalidAccounts.Count);
  241. report.DateActionTaken = DateTime.Now;
  242. db.Takedowns.Add(report);
  243. db.SaveChanges();
  244. }
  245. // Delete inactive accounts
  246. foreach (string account in inactiveAccounts)
  247. {
  248. UserHelper.DeleteAccount(db, config, UserHelper.GetUser(db, account));
  249. }
  250. if (invalidAccounts.Count > 0)
  251. {
  252. // Add to transparency report if any users were removed
  253. Takedown report = db.Takedowns.Create();
  254. report.Requester = TAKEDOWN_REPORTER;
  255. report.RequesterContact = config.SupportEmail;
  256. report.DateRequested = DateTime.Now;
  257. report.Reason = "Account Inactive";
  258. report.ActionTaken = string.Format("{0} Accounts Removed", inactiveAccounts.Count);
  259. report.DateActionTaken = DateTime.Now;
  260. db.Takedowns.Add(report);
  261. db.SaveChanges();
  262. }
  263. Output(string.Format("[{0}] Finished Cleaning of Inactive/Invalid Users. {1} Accounts Removed.", DateTime.Now, invalidAccounts.Count + inactiveAccounts.Count));
  264. }
  265. public static void CleanEmail(Config config, TeknikEntities db)
  266. {
  267. Output(string.Format("[{0}] Started Cleaning of Orphaned Email Accounts.", DateTime.Now));
  268. List<string> emails = GetOrphanedEmail(config, db);
  269. foreach (string email in emails)
  270. {
  271. // User doesn't exist, and it isn't reserved. Let's nuke it.
  272. UserHelper.DeleteUserEmail(config, email);
  273. }
  274. if (emails.Count > 0)
  275. {
  276. // Add to transparency report if any users were removed
  277. Takedown report = db.Takedowns.Create();
  278. report.Requester = TAKEDOWN_REPORTER;
  279. report.RequesterContact = config.SupportEmail;
  280. report.DateRequested = DateTime.Now;
  281. report.Reason = "Orphaned Email Account";
  282. report.ActionTaken = string.Format("{0} Accounts Removed", emails.Count);
  283. report.DateActionTaken = DateTime.Now;
  284. db.Takedowns.Add(report);
  285. db.SaveChanges();
  286. }
  287. Output(string.Format("[{0}] Finished Cleaning of Orphaned Email Accounts. {1} Accounts Removed.", DateTime.Now, emails.Count));
  288. }
  289. public static void CleanGit(Config config, TeknikEntities db)
  290. {
  291. Output(string.Format("[{0}] Started Cleaning of Orphaned Git Accounts.", DateTime.Now));
  292. List<string> gitAccounts = GetOrphanedGit(config, db);
  293. foreach (string account in gitAccounts)
  294. {
  295. // User doesn't exist, and it isn't reserved. Let's nuke it.
  296. UserHelper.DeleteUserGit(config, account);
  297. }
  298. if (gitAccounts.Count > 0)
  299. {
  300. // Add to transparency report if any users were removed
  301. Takedown report = db.Takedowns.Create();
  302. report.Requester = TAKEDOWN_REPORTER;
  303. report.RequesterContact = config.SupportEmail;
  304. report.DateRequested = DateTime.Now;
  305. report.Reason = "Orphaned Git Account";
  306. report.ActionTaken = string.Format("{0} Accounts Removed", gitAccounts.Count);
  307. report.DateActionTaken = DateTime.Now;
  308. db.Takedowns.Add(report);
  309. db.SaveChanges();
  310. }
  311. Output(string.Format("[{0}] Finished Cleaning of Orphaned Git Accounts. {1} Accounts Removed.", DateTime.Now, gitAccounts.Count));
  312. }
  313. public static void GenerateLastSeen(Config config, TeknikEntities db, string fileName)
  314. {
  315. Output(string.Format("[{0}] Started Generation of Last Activity List.", DateTime.Now));
  316. List<User> curUsers = db.Users.ToList();
  317. StringBuilder sb = new StringBuilder();
  318. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  319. foreach (User user in curUsers)
  320. {
  321. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  322. user.Username,
  323. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  324. user.JoinDate.ToString("g"),
  325. user.LastSeen.ToString("g"),
  326. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  327. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  328. }
  329. string dir = Path.GetDirectoryName(fileName);
  330. if (!Directory.Exists(dir))
  331. Directory.CreateDirectory(dir);
  332. File.WriteAllText(fileName, sb.ToString());
  333. Output(string.Format("[{0}] Finished Generating Last Activity List.", DateTime.Now));
  334. }
  335. public static void GenerateInvalidAccounts(Config config, TeknikEntities db, string fileName)
  336. {
  337. Output(string.Format("[{0}] Started Generation of Invalid Account List.", DateTime.Now));
  338. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  339. StringBuilder sb = new StringBuilder();
  340. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  341. foreach (string account in invalidAccounts)
  342. {
  343. User user = UserHelper.GetUser(db, account);
  344. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  345. user.Username,
  346. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  347. user.JoinDate.ToString("g"),
  348. user.LastSeen.ToString("g"),
  349. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  350. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  351. }
  352. string dir = Path.GetDirectoryName(fileName);
  353. if (!Directory.Exists(dir))
  354. Directory.CreateDirectory(dir);
  355. File.WriteAllText(fileName, sb.ToString());
  356. Output(string.Format("[{0}] Finished Generating Invalid Account List.", DateTime.Now));
  357. }
  358. public static void GenerateCleaningList(Config config, TeknikEntities db, string fileName, int maxDays)
  359. {
  360. Output(string.Format("[{0}] Started Generation of Accounts to Clean List.", DateTime.Now));
  361. List<string> invalidAccounts = GetInvalidAccounts(config, db);
  362. List<string> inactiveAccounts = GetInactiveAccounts(config, db, maxDays);
  363. List<string> emailAccounts = GetOrphanedEmail(config, db);
  364. List<string> gitAccounts = GetOrphanedGit(config, db);
  365. StringBuilder sb = new StringBuilder();
  366. sb.AppendLine("Invalid Account Cleaning");
  367. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  368. foreach (string account in invalidAccounts)
  369. {
  370. User user = UserHelper.GetUser(db, account);
  371. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  372. user.Username,
  373. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  374. user.JoinDate.ToString("g"),
  375. user.LastSeen.ToString("g"),
  376. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  377. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  378. }
  379. sb.AppendLine();
  380. sb.AppendLine("Inactive Account Cleaning");
  381. sb.AppendLine("Username,Last Activity,Creation Date,Last Website Activity,Last Email Activity,Last Git Activity");
  382. foreach (string account in inactiveAccounts)
  383. {
  384. User user = UserHelper.GetUser(db, account);
  385. sb.AppendLine(string.Format("{0},{1},{2},{3},{4},{5}",
  386. user.Username,
  387. UserHelper.GetLastAccountActivity(db, config, user).ToString("g"),
  388. user.JoinDate.ToString("g"),
  389. user.LastSeen.ToString("g"),
  390. UserHelper.UserEmailLastActive(config, UserHelper.GetUserEmailAddress(config, user.Username)).ToString("g"),
  391. UserHelper.UserGitLastActive(config, user.Username).ToString("g")));
  392. }
  393. sb.AppendLine();
  394. sb.AppendLine("Orphaned Email Cleaning");
  395. sb.AppendLine("Email,Last Activity");
  396. foreach (string account in emailAccounts)
  397. {
  398. sb.AppendLine(string.Format("{0},{1}",
  399. account,
  400. UserHelper.UserEmailLastActive(config, account).ToString("g")));
  401. }
  402. sb.AppendLine();
  403. sb.AppendLine("Orphaned Git Cleaning");
  404. sb.AppendLine("Username,Last Activity");
  405. foreach (string account in gitAccounts)
  406. {
  407. sb.AppendLine(string.Format("{0},{1}",
  408. account,
  409. UserHelper.UserGitLastActive(config, account).ToString("g")));
  410. }
  411. string dir = Path.GetDirectoryName(fileName);
  412. if (!Directory.Exists(dir))
  413. Directory.CreateDirectory(dir);
  414. File.WriteAllText(fileName, sb.ToString());
  415. Output(string.Format("[{0}] Finished Generating Accounts to Clean List.", DateTime.Now));
  416. }
  417. public static List<string> GetInvalidAccounts(Config config, TeknikEntities db)
  418. {
  419. List<string> foundUsers = new List<string>();
  420. List<User> curUsers = db.Users.ToList();
  421. foreach (User user in curUsers)
  422. {
  423. // If the username is reserved, let's add it to the list
  424. if (UserHelper.UsernameReserved(config, user.Username))
  425. {
  426. foundUsers.Add(user.Username);
  427. continue;
  428. }
  429. // If the username is invalid, let's add it to the list
  430. if (!UserHelper.ValidUsername(config, user.Username) && user.Username != "Server Admin")
  431. {
  432. foundUsers.Add(user.Username);
  433. continue;
  434. }
  435. }
  436. return foundUsers;
  437. }
  438. public static List<string> GetInactiveAccounts(Config config, TeknikEntities db, int maxDays)
  439. {
  440. List<string> foundUsers = new List<string>();
  441. List<User> curUsers = db.Users.ToList();
  442. foreach (User user in curUsers)
  443. {
  444. // If the username is reserved, don't worry about it
  445. if (UserHelper.UsernameReserved(config, user.Username))
  446. {
  447. continue;
  448. }
  449. #region Inactivity Finding
  450. DateTime lastActivity = UserHelper.GetLastAccountActivity(db, config, user);
  451. TimeSpan inactiveTime = DateTime.Now.Subtract(lastActivity);
  452. // If older than max days, check their current usage
  453. if (inactiveTime >= new TimeSpan(maxDays, 0, 0, 0, 0))
  454. {
  455. // Check the user's usage of the service.
  456. bool noData = true;
  457. // Any blog comments?
  458. var blogCom = db.BlogComments.Where(c => c.UserId == user.UserId);
  459. noData &= !(blogCom != null && blogCom.Any());
  460. // Any blog posts?
  461. var blogPosts = db.BlogPosts.Where(p => p.Blog.UserId == user.UserId);
  462. noData &= !(blogPosts != null && blogPosts.Any());
  463. // Any podcast comments?
  464. var podCom = db.PodcastComments.Where(p => p.UserId == user.UserId);
  465. noData &= !(podCom != null && podCom.Any());
  466. // Any email?
  467. if (config.EmailConfig.Enabled)
  468. {
  469. var app = new hMailServer.Application();
  470. app.Connect();
  471. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  472. try
  473. {
  474. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  475. var account = domain.Accounts.ItemByAddress[UserHelper.GetUserEmailAddress(config, user.Username)];
  476. noData &= ((account.Messages.Count == 0) && ((int)account.Size == 0));
  477. }
  478. catch { }
  479. }
  480. // Any git repos?
  481. if (config.GitConfig.Enabled)
  482. {
  483. string email = UserHelper.GetUserEmailAddress(config, user.Username);
  484. // We need to check the actual git database
  485. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database);
  486. string sql = @"SELECT * FROM gogs.repository
  487. LEFT JOIN gogs.action ON gogs.user.id = gogs.action.act_user_id
  488. WHERE gogs.user.login_name = {0}";
  489. var results = mySQL.Query(sql, new object[] { email });
  490. noData &= !(results != null && results.Any());
  491. }
  492. if (noData)
  493. {
  494. // They have no data, so safe to delete them.
  495. foundUsers.Add(user.Username);
  496. }
  497. continue;
  498. }
  499. #endregion
  500. }
  501. return foundUsers;
  502. }
  503. public static List<string> GetOrphanedEmail(Config config, TeknikEntities db)
  504. {
  505. List<string> foundEmail = new List<string>();
  506. if (config.EmailConfig.Enabled)
  507. {
  508. List<User> curUsers = db.Users.ToList();
  509. // Connect to hmailserver COM
  510. var app = new hMailServer.Application();
  511. app.Connect();
  512. app.Authenticate(config.EmailConfig.Username, config.EmailConfig.Password);
  513. var domain = app.Domains.ItemByName[config.EmailConfig.Domain];
  514. var accounts = domain.Accounts;
  515. for (int i = 0; i < accounts.Count; i++)
  516. {
  517. var account = accounts[i];
  518. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username) == account.Address);
  519. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r).ToLower() == account.Address.ToLower());
  520. if (!userExists && !isReserved)
  521. {
  522. foundEmail.Add(account.Address);
  523. }
  524. }
  525. }
  526. return foundEmail;
  527. }
  528. public static List<string> GetOrphanedGit(Config config, TeknikEntities db)
  529. {
  530. List<string> foundGit = new List<string>();
  531. if (config.GitConfig.Enabled)
  532. {
  533. List<User> curUsers = db.Users.ToList();
  534. // We need to check the actual git database
  535. MysqlDatabase mySQL = new MysqlDatabase(config.GitConfig.Database);
  536. string sql = @"SELECT gogs.user.login_name AS login_name, gogs.user.lower_name AS username FROM gogs.user";
  537. var results = mySQL.Query(sql);
  538. if (results != null && results.Any())
  539. {
  540. foreach (var account in results)
  541. {
  542. bool userExists = curUsers.Exists(u => UserHelper.GetUserEmailAddress(config, u.Username).ToLower() == account["login_name"].ToString().ToLower());
  543. bool isReserved = UserHelper.GetReservedUsernames(config).Exists(r => UserHelper.GetUserEmailAddress(config, r) == account["login_name"].ToString().ToLower());
  544. if (!userExists && !isReserved)
  545. {
  546. foundGit.Add(account["username"].ToString());
  547. }
  548. }
  549. }
  550. }
  551. return foundGit;
  552. }
  553. public static void Output(string message)
  554. {
  555. Console.WriteLine(message);
  556. if (OutputEvent != null)
  557. {
  558. OutputEvent(message);
  559. }
  560. }
  561. }
  562. }