CCMain.m 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCBridgeSwift.h"
  37. #import "NCNetworkingSync.h"
  38. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  39. {
  40. tableMetadata *_metadata;
  41. BOOL _isRoot;
  42. BOOL _isViewDidLoad;
  43. BOOL _isSelectedMode;
  44. NSMutableDictionary *_selectedFileIDsMetadatas;
  45. NSUInteger _numSelectedFileIDsMetadatas;
  46. NSMutableArray *_queueSelector;
  47. NSMutableDictionary *_statusSwipeCell;
  48. UIImageView *_ImageTitleHomeCryptoCloud;
  49. UIView *_reMenuBackgroundView;
  50. UITapGestureRecognizer *_singleFingerTap;
  51. NSString *_directoryGroupBy;
  52. NSString *_directoryOrder;
  53. NSUInteger _failedAttempts;
  54. NSDate *_lockUntilDate;
  55. NSString *_fatherPermission;
  56. UIRefreshControl *_refreshControl;
  57. UIDocumentInteractionController *_docController;
  58. CCHud *_hud;
  59. CCHud *_hudDeterminate;
  60. // Datasource
  61. CCSectionDataSourceMetadata *_sectionDataSource;
  62. NSDate *_dateReadDataSource;
  63. // Search
  64. BOOL _isSearchMode;
  65. NSString *_searchFileName;
  66. NSMutableArray *_searchResultMetadatas;
  67. NSString *_noFilesSearchTitle;
  68. NSString *_noFilesSearchDescription;
  69. NSTimer *_timerWaitInput;
  70. // Login
  71. CCLoginWeb *_loginWeb;
  72. CCLogin *_loginVC;
  73. // Automatic Upload Folder
  74. NSString *_autoUploadFileName;
  75. NSString *_autoUploadDirectory;
  76. BOOL _loadingFolder;
  77. // e2e
  78. BOOL _folderEncrypted;
  79. }
  80. @end
  81. @implementation CCMain
  82. #pragma --------------------------------------------------------------------------------------------
  83. #pragma mark ===== Init =====
  84. #pragma --------------------------------------------------------------------------------------------
  85. - (id)initWithCoder:(NSCoder *)aDecoder
  86. {
  87. if (self = [super initWithCoder:aDecoder]) {
  88. _directoryOrder = [CCUtility getOrderSettings];
  89. _directoryGroupBy = [CCUtility getGroupBySettings];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  91. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  92. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  93. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  94. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  95. }
  96. return self;
  97. }
  98. #pragma --------------------------------------------------------------------------------------------
  99. #pragma mark ===== View =====
  100. #pragma --------------------------------------------------------------------------------------------
  101. - (void)viewDidLoad
  102. {
  103. [super viewDidLoad];
  104. // init object
  105. _metadata = [tableMetadata new];
  106. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  107. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  108. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  109. _statusSwipeCell = [NSMutableDictionary new];
  110. _queueSelector = [NSMutableArray new];
  111. _isViewDidLoad = YES;
  112. _fatherPermission = @"";
  113. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  114. _searchResultMetadatas = [NSMutableArray new];
  115. _searchFileName = @"";
  116. _noFilesSearchTitle = @"";
  117. _noFilesSearchDescription = @"";
  118. // delegate
  119. self.tableView.delegate = self;
  120. self.tableView.tableFooterView = [UIView new];
  121. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  122. self.tableView.emptyDataSetDelegate = self;
  123. self.tableView.emptyDataSetSource = self;
  124. self.searchController.delegate = self;
  125. self.searchController.searchBar.delegate = self;
  126. [CCNetworking sharedNetworking].delegate = self;
  127. // Custom Cell
  128. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  129. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  130. // long press recognizer TableView
  131. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  132. [self.tableView addGestureRecognizer:longPressRecognizer];
  133. // Pull-to-Refresh
  134. [self createRefreshControl];
  135. // Register for 3D Touch Previewing if available
  136. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  137. {
  138. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  139. }
  140. // Back Button
  141. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  142. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  143. // reMenu Background
  144. _reMenuBackgroundView = [[UIView alloc] init];
  145. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  146. // if this is not Main (the Main uses inizializeMain)
  147. if (_isRoot == NO && app.activeAccount.length > 0) {
  148. // Settings this folder & delegate & Loading datasource
  149. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  150. // Load Datasource
  151. [self reloadDatasource:_serverUrl];
  152. // Read (File) Folder
  153. [self readFileReloadFolder];
  154. }
  155. // Title
  156. [self setTitle];
  157. }
  158. // Apparirà
  159. - (void)viewWillAppear:(BOOL)animated
  160. {
  161. [super viewWillAppear:animated];
  162. // test
  163. if (app.activeAccount.length == 0)
  164. return;
  165. // Settings this folder & delegate & Loading datasource
  166. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  167. [CCNetworking sharedNetworking].delegate = self;
  168. // Color
  169. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  170. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  171. if (_isSelectedMode)
  172. [self setUINavigationBarSelected];
  173. else
  174. [self setUINavigationBarDefault];
  175. // If not editing mode remove _selectedFileIDs
  176. if (!self.tableView.editing)
  177. [_selectedFileIDsMetadatas removeAllObjects];
  178. // Plus Button
  179. [app plusButtonVisibile:true];
  180. //
  181. if ([CCUtility isFolderEncrypted:self.serverUrl account:app.activeAccount]) {
  182. [self searchEnabled:NO];
  183. } else {
  184. [self searchEnabled:YES];
  185. }
  186. }
  187. // E' arrivato
  188. - (void)viewDidAppear:(BOOL)animated
  189. {
  190. [super viewDidAppear:animated];
  191. // Active Main
  192. app.activeMain = self;
  193. // Test viewDidLoad
  194. if (_isViewDidLoad) {
  195. _isViewDidLoad = NO;
  196. } else {
  197. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  198. // Load Datasource
  199. [self reloadDatasource:_serverUrl];
  200. // Read (file) Folder
  201. [self readFileReloadFolder];
  202. }
  203. }
  204. // Title
  205. [self setTitle];
  206. }
  207. - (void)viewWillDisappear:(BOOL)animated
  208. {
  209. [super viewWillDisappear:animated];
  210. [self closeAllMenu];
  211. }
  212. - (void)didReceiveMemoryWarning
  213. {
  214. [super didReceiveMemoryWarning];
  215. // Dispose of any resources that can be recreated.
  216. }
  217. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  218. {
  219. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  220. [self closeAllMenu];
  221. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  222. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  223. // Portrait
  224. } else {
  225. // Landscape
  226. }
  227. [self.tableView reloadData];
  228. }];
  229. }
  230. - (BOOL)prefersStatusBarHidden
  231. {
  232. return NO;
  233. }
  234. // detect scroll for remove keyboard in search mode
  235. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  236. {
  237. if (_isSearchMode && scrollView == self.tableView) {
  238. [self.searchController.searchBar endEditing:YES];
  239. }
  240. }
  241. - (void)changeTheming
  242. {
  243. if (self.isViewLoaded && self.view.window)
  244. [app changeTheming:self];
  245. // Refresh control
  246. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  247. // Reload Table View
  248. [self tableViewReloadData];
  249. }
  250. #pragma --------------------------------------------------------------------------------------------
  251. #pragma mark ===== Initizlize Mail =====
  252. #pragma --------------------------------------------------------------------------------------------
  253. - (void)initializeMain:(NSNotification *)notification
  254. {
  255. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  256. _directoryGroupBy = nil;
  257. _directoryOrder = nil;
  258. _dateReadDataSource = nil;
  259. // test
  260. if (app.activeAccount.length == 0)
  261. return;
  262. if ([app.listMainVC count] == 0 || _isRoot) {
  263. // This is Root home main add list
  264. appDelegate.homeMain = self;
  265. _isRoot = YES;
  266. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  267. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  268. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  269. // go Home
  270. [self.navigationController popToRootViewControllerAnimated:NO];
  271. // setting Networking
  272. [CCNetworking sharedNetworking].delegate = self;
  273. [[CCNetworking sharedNetworking] settingAccount];
  274. // Remove search mode
  275. [self cancelSearchBar];
  276. // populate shared Link & User
  277. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  278. if (results) {
  279. appDelegate.sharesLink = results[0];
  280. appDelegate.sharesUserAndGroup = results[1];
  281. }
  282. // Load Datasource
  283. [self reloadDatasource:_serverUrl];
  284. // Read (File) Folder
  285. [self readFileReloadFolder];
  286. // Setting Theming
  287. [app settingThemingColorBrand];
  288. // Load photo datasorce
  289. if (appDelegate.activePhotos)
  290. [appDelegate.activePhotos reloadDatasourceForced];
  291. // remove all of detail
  292. if (appDelegate.activeDetail)
  293. [appDelegate.activeDetail removeAllView];
  294. // remove all Notification Messages
  295. [appDelegate.listOfNotifications removeAllObjects];
  296. // Not Photos Video in library ? then align
  297. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  298. if ([recordsPhotoLibrary count] == 0) {
  299. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  300. }
  301. // Initializations
  302. [appDelegate applicationInitialized];
  303. } else {
  304. // reload datasource
  305. [self reloadDatasource:_serverUrl];
  306. }
  307. }
  308. #pragma --------------------------------------------------------------------------------------------
  309. #pragma mark ==== DZNEmptyDataSetSource ====
  310. #pragma --------------------------------------------------------------------------------------------
  311. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  312. {
  313. if (_loadingFolder)
  314. return NO;
  315. else
  316. return YES;
  317. }
  318. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  319. {
  320. return [UIColor whiteColor];
  321. }
  322. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  323. {
  324. if (_isSearchMode)
  325. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  326. else
  327. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  328. }
  329. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  330. {
  331. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  332. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  333. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  334. activityView.color = [NCBrandColor sharedInstance].brand;
  335. [activityView startAnimating];
  336. return activityView;
  337. }
  338. return nil;
  339. }
  340. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  341. {
  342. NSString *text;
  343. if (_isSearchMode) {
  344. text = _noFilesSearchTitle;
  345. } else {
  346. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  347. }
  348. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  349. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  350. }
  351. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  352. {
  353. NSString *text;
  354. if (_isSearchMode) {
  355. text = _noFilesSearchDescription;
  356. } else {
  357. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  358. }
  359. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  360. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  361. paragraph.alignment = NSTextAlignmentCenter;
  362. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  363. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  364. }
  365. #pragma --------------------------------------------------------------------------------------------
  366. #pragma mark ===== Text Field =====
  367. #pragma --------------------------------------------------------------------------------------------
  368. - (void)minCharTextFieldDidChange:(UITextField *)sender
  369. {
  370. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  371. if (alertController)
  372. {
  373. UITextField *fileName = alertController.textFields.firstObject;
  374. UIAlertAction *okAction = alertController.actions.lastObject;
  375. okAction.enabled = fileName.text.length > 0;
  376. }
  377. }
  378. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  379. [textField selectAll:textField];
  380. }
  381. #pragma --------------------------------------------------------------------------------------------
  382. #pragma mark ===== Graphic Window =====
  383. #pragma --------------------------------------------------------------------------------------------
  384. - (void)createRefreshControl
  385. {
  386. _refreshControl = [UIRefreshControl new];
  387. if (@available(iOS 11, *)) {
  388. [self.tableView setRefreshControl:_refreshControl];
  389. _refreshControl.tintColor = [UIColor whiteColor];
  390. } else {
  391. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  392. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  393. [self setRefreshControl:_refreshControl];
  394. }
  395. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  396. }
  397. - (void)deleteRefreshControl
  398. {
  399. [_refreshControl endRefreshing];
  400. self.refreshControl = nil;
  401. }
  402. - (void)refreshControlTarget
  403. {
  404. [self readFolder:_serverUrl];
  405. // Actuate `Peek` feedback (weak boom)
  406. AudioServicesPlaySystemSound(1519);
  407. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  408. }
  409. - (void)setTitle
  410. {
  411. // Color text self.navigationItem.title
  412. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  413. if (_isSelectedMode) {
  414. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  415. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  416. self.navigationItem.titleView = nil;
  417. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  418. } else {
  419. // we are in home : LOGO BRAND
  420. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  421. self.navigationItem.title = nil;
  422. if ([app.reachability isReachable] == NO)
  423. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  424. else
  425. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  426. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  427. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  428. [singleTap setNumberOfTapsRequired:1];
  429. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  430. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  431. } else {
  432. self.navigationItem.title = _titleMain;
  433. }
  434. }
  435. }
  436. - (void)setUINavigationBarDefault
  437. {
  438. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  439. UIBarButtonItem *buttonMore, *buttonNotification;
  440. // =
  441. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  442. buttonMore.enabled = true;
  443. // <
  444. self.navigationController.navigationBar.hidden = NO;
  445. // Notification
  446. if ([app.listOfNotifications count] > 0) {
  447. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  448. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  449. buttonNotification.enabled = true;
  450. }
  451. if (buttonNotification)
  452. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  453. else
  454. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  455. self.navigationItem.leftBarButtonItem = nil;
  456. }
  457. - (void)setUINavigationBarSelected
  458. {
  459. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  460. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  461. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  462. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  463. self.navigationItem.leftBarButtonItem = leftButton;
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  465. }
  466. - (void)cancelSelect
  467. {
  468. [self tableViewSelect:NO];
  469. [app.reSelectMenu close];
  470. }
  471. - (void)closeAllMenu
  472. {
  473. // close Menu
  474. [app.reSelectMenu close];
  475. [app.reMainMenu close];
  476. // Close Menu Logo
  477. [CCMenuAccount dismissMenu];
  478. }
  479. #pragma --------------------------------------------------------------------------------------------
  480. #pragma mark ===== Document Picker =====
  481. #pragma --------------------------------------------------------------------------------------------
  482. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  483. {
  484. NSLog(@"[LOG] Cancelled");
  485. }
  486. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  487. {
  488. NSLog(@"[LOG] Cancelled");
  489. }
  490. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  491. {
  492. documentPicker.delegate = self;
  493. [self presentViewController:documentPicker animated:YES completion:nil];
  494. }
  495. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  496. {
  497. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  498. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  499. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  500. __block NSError *error;
  501. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  502. NSString *fileName = [url lastPathComponent];
  503. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  504. NSData *data = [NSData dataWithContentsOfURL:newURL];
  505. if (data && error == nil) {
  506. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  507. // Upload File
  508. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  509. } else {
  510. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  511. }
  512. } else {
  513. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  514. }
  515. }];
  516. }
  517. }
  518. - (void)openImportDocumentPicker
  519. {
  520. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  521. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  522. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  523. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  524. documentProviderMenu.delegate = self;
  525. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  526. }
  527. #pragma --------------------------------------------------------------------------------------------
  528. #pragma mark ===== Assets Picker =====
  529. #pragma --------------------------------------------------------------------------------------------
  530. -(void)dismissFormUploadAssets
  531. {
  532. [self reloadDatasource];
  533. }
  534. - (void)openAssetsPickerController
  535. {
  536. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  537. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  538. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  539. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  540. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  541. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  542. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  543. dispatch_async(dispatch_get_main_queue(), ^{
  544. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  545. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  546. // init picker
  547. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  548. // set delegate
  549. picker.delegate = self;
  550. // to show selection order
  551. //picker.showsSelectionIndex = YES;
  552. // to present picker as a form sheet in iPad
  553. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  554. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  555. // present picker
  556. [self presentViewController:picker animated:YES completion:nil];
  557. });
  558. }];
  559. }
  560. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  561. {
  562. if (picker.selectedAssets.count > k_pickerControllerMax) {
  563. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  564. return NO;
  565. }
  566. return YES;
  567. }
  568. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  569. {
  570. [picker dismissViewControllerAnimated:YES completion:^{
  571. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  572. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  573. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  574. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  575. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  576. [self presentViewController:navigationController animated:YES completion:nil];
  577. }];
  578. }
  579. // New folder or new photo or video
  580. - (void)returnCreate:(NSInteger)type
  581. {
  582. switch (type) {
  583. case k_returnCreateFolderPlain: {
  584. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  585. NSString *message;
  586. UIAlertController *alertController;
  587. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  588. message = @"/";
  589. } else {
  590. message = [serverUrl lastPathComponent];
  591. }
  592. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  593. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  594. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  595. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  596. }];
  597. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  598. NSLog(@"[LOG] Cancel action");
  599. }];
  600. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  601. UITextField *fileName = alertController.textFields.firstObject;
  602. [self createFolder:fileName.text serverUrl:serverUrl];
  603. }];
  604. okAction.enabled = NO;
  605. [alertController addAction:cancelAction];
  606. [alertController addAction:okAction];
  607. [self presentViewController:alertController animated:YES completion:nil];
  608. }
  609. break;
  610. case k_returnCreateFotoVideoPlain: {
  611. [self openAssetsPickerController];
  612. }
  613. break;
  614. case k_returnCreateFilePlain: {
  615. [self openImportDocumentPicker];
  616. }
  617. break;
  618. case k_returnCreateFotoVideoEncrypted: {
  619. [self openAssetsPickerController];
  620. }
  621. break;
  622. case k_returnCreateFileEncrypted: {
  623. [self openImportDocumentPicker];
  624. }
  625. break;
  626. case k_returnCreateFileText: {
  627. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  628. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  629. [self presentViewController:navigationController animated:YES completion:nil];
  630. }
  631. break;
  632. }
  633. }
  634. #pragma --------------------------------------------------------------------------------------------
  635. #pragma mark ===== Save selected File =====
  636. #pragma --------------------------------------------------------------------------------------------
  637. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  638. {
  639. if (error)
  640. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  641. else
  642. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  643. }
  644. - (void)saveSelectedFiles
  645. {
  646. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  647. return;
  648. NSLog(@"[LOG] Start download selected files ...");
  649. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  650. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  651. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  652. for (tableMetadata *metadata in metadatas) {
  653. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  654. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  655. if (serverUrl)
  656. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  657. }
  658. }
  659. [_hud hideHud];
  660. });
  661. [self tableViewSelect:NO];
  662. }
  663. #pragma --------------------------------------------------------------------------------------------
  664. #pragma mark === Delegate Login ===
  665. #pragma --------------------------------------------------------------------------------------------
  666. - (void)loginSuccess:(NSInteger)loginType
  667. {
  668. [self readFolder:_serverUrl];
  669. }
  670. - (void)loginDisappear
  671. {
  672. app.activeLogin = nil;
  673. }
  674. #pragma mark -
  675. #pragma --------------------------------------------------------------------------------------------
  676. #pragma mark ===== Peek & Pop =====
  677. #pragma --------------------------------------------------------------------------------------------
  678. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  679. {
  680. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  681. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  682. if (metadata.thumbnailExists) {
  683. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  684. if (cell) {
  685. previewingContext.sourceRect = cell.frame;
  686. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  687. vc.delegate = self;
  688. vc.metadata = metadata;
  689. return vc;
  690. }
  691. }
  692. return nil;
  693. }
  694. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  695. {
  696. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  697. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  698. }
  699. #pragma mark -
  700. #pragma --------------------------------------------------------------------------------------------
  701. #pragma mark ==== External Sites ====
  702. #pragma --------------------------------------------------------------------------------------------
  703. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  704. {
  705. [[NCManageDatabase sharedInstance] deleteExternalSites];
  706. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  707. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  708. }
  709. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  710. {
  711. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  712. NSLog(@"[LOG] %@", error);
  713. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  714. }
  715. #pragma --------------------------------------------------------------------------------------------
  716. #pragma mark ==== Activity ====
  717. #pragma --------------------------------------------------------------------------------------------
  718. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  719. {
  720. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  721. // Reload Activity Data Source
  722. [app.activeActivity reloadDatasource];
  723. }
  724. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  725. {
  726. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  727. NSLog(@"[LOG] %@", error);
  728. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  729. }
  730. #pragma --------------------------------------------------------------------------------------------
  731. #pragma mark ==== Notification ====
  732. #pragma --------------------------------------------------------------------------------------------
  733. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  734. {
  735. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  736. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  737. // Order by date
  738. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  739. OCNotifications *notification1 = obj1, *notification2 = obj2;
  740. return [notification2.date compare: notification1.date];
  741. }];
  742. // verify if listOfNotifications is changed
  743. NSString *old = @"", *new = @"";
  744. for (OCNotifications *notification in listOfNotifications)
  745. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  746. for (OCNotifications *notification in appDelegate.listOfNotifications)
  747. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  748. if (![new isEqualToString:old]) {
  749. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  750. // reload Notification view
  751. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  752. }
  753. // Update NavigationBar
  754. if (!_isSelectedMode) {
  755. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  756. }
  757. });
  758. }
  759. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  760. {
  761. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  762. NSLog(@"[LOG] %@", error);
  763. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  764. // Update NavigationBar
  765. if (!_isSelectedMode)
  766. [self setUINavigationBarDefault];
  767. }
  768. - (void)viewNotification
  769. {
  770. if ([app.listOfNotifications count] > 0) {
  771. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  772. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  773. [self presentViewController:notificationVC animated:YES completion:nil];
  774. }
  775. }
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ==== User Profile ====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  780. {
  781. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  782. NSLog(@"[LOG] %@", error);
  783. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  784. }
  785. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  786. {
  787. // Update User (+ userProfile.id)
  788. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  789. // Get Account Active
  790. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  791. // Setting App active account
  792. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  793. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  794. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  795. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  796. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  797. if (avatar)
  798. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  799. else
  800. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  801. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  802. });
  803. }
  804. #pragma --------------------------------------------------------------------------------------------
  805. #pragma mark ==== Capabilities ====
  806. #pragma --------------------------------------------------------------------------------------------
  807. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  808. {
  809. // Unauthorized
  810. if (errorCode == kOCErrorServerUnauthorized)
  811. [app openLoginView:self loginType:loginModifyPasswordUser];
  812. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  813. NSLog(@"[LOG] %@", error);
  814. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  815. // Change Theming color
  816. [app settingThemingColorBrand];
  817. }
  818. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  819. {
  820. // Update capabilities db
  821. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  822. // ------ THEMING -----------------------------------------------------------------------
  823. // Download Theming Background & Change Theming color
  824. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  825. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  826. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  827. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  828. if (themingBackground) {
  829. dispatch_async(dispatch_get_main_queue(), ^{
  830. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  831. });
  832. } else {
  833. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  834. }
  835. }
  836. dispatch_async(dispatch_get_main_queue(), ^{
  837. [app settingThemingColorBrand];
  838. });
  839. });
  840. // ------ SEARCH ------------------------------------------------------------------------
  841. // Search bar if change version
  842. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  843. [self cancelSearchBar];
  844. }
  845. // ------ GET SERVICE SERVER ------------------------------------------------------------
  846. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  847. // Read External Sites
  848. if (capabilities.isExternalSitesServerEnabled) {
  849. metadataNet.action = actionGetExternalSitesServer;
  850. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  851. }
  852. // Read Share
  853. if (capabilities.isFilesSharingAPIEnabled) {
  854. [app.sharesID removeAllObjects];
  855. metadataNet.action = actionReadShareServer;
  856. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  857. }
  858. // Read Notification
  859. metadataNet.action = actionGetNotificationServer;
  860. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  861. // Read User Profile
  862. metadataNet.action = actionGetUserProfile;
  863. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  864. // Read Activity
  865. metadataNet.action = actionGetActivityServer;
  866. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  867. }
  868. #pragma mark -
  869. #pragma --------------------------------------------------------------------------------------------
  870. #pragma mark ==== Request Server Information ====
  871. #pragma --------------------------------------------------------------------------------------------
  872. - (void)requestServerCapabilities
  873. {
  874. // test
  875. if (app.activeAccount.length == 0)
  876. return;
  877. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  878. metadataNet.action = actionGetCapabilities;
  879. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  880. }
  881. #pragma mark -
  882. #pragma --------------------------------------------------------------------------------------------
  883. #pragma mark ==== Middleware Ping ====
  884. #pragma --------------------------------------------------------------------------------------------
  885. - (void)middlewarePing
  886. {
  887. // test
  888. if (app.activeAccount.length == 0)
  889. return;
  890. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  891. metadataNet.action = actionMiddlewarePing;
  892. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  893. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  894. }
  895. #pragma mark -
  896. #pragma --------------------------------------------------------------------------------------------
  897. #pragma mark ==== Download Thumbnail Delegate ====
  898. #pragma --------------------------------------------------------------------------------------------
  899. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  900. {
  901. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  902. }
  903. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  904. {
  905. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  906. if ([self indexPathIsValid:indexPath]) {
  907. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  908. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  909. }
  910. }
  911. #pragma --------------------------------------------------------------------------------------------
  912. #pragma mark ==== Download ====
  913. #pragma --------------------------------------------------------------------------------------------
  914. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  915. {
  916. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  917. // File do not exists on server, remove in local
  918. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  919. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  920. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  921. if (metadata.directory && serverUrl) {
  922. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  923. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  924. }
  925. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  926. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  927. }
  928. if ([selector isEqualToString:selectorLoadViewImage]) {
  929. dispatch_async(dispatch_get_main_queue(), ^{
  930. // Updating Detail
  931. if (app.activeDetail)
  932. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  933. // Updating Photos
  934. if (app.activePhotos)
  935. [app.activePhotos downloadFileFailure:errorCode];
  936. });
  937. } else {
  938. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  939. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  940. }
  941. [self reloadDatasource:serverUrl];
  942. }
  943. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  944. {
  945. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  946. if (metadata == nil)
  947. return;
  948. tableE2eEncryption *e2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"fileNameIdentifier = %@ AND serverUrl = %@", metadata.fileName, serverUrl]];
  949. if (e2eEncryption) {
  950. metadata.e2eEncrypted = true;
  951. metadata.fileNameView = e2eEncryption.fileName;
  952. [CCUtility insertTypeFileIconName:e2eEncryption.fileName metadata:metadata];
  953. }
  954. // Download
  955. if ([selector isEqualToString:selectorDownloadFile]) {
  956. [self reloadDatasource:serverUrl];
  957. }
  958. // Synchronized
  959. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  960. [self reloadDatasource:serverUrl];
  961. }
  962. // add Favorite
  963. if ([selector isEqualToString:selectorAddFavorite]) {
  964. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  965. }
  966. // open View File
  967. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  968. [self reloadDatasource:serverUrl];
  969. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  970. selector = selectorOpenIn;
  971. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  972. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  973. selector = selectorOpenIn;
  974. } else {
  975. _metadata = metadata;
  976. if ([self shouldPerformSegue])
  977. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  978. }
  979. }
  980. // Open with...
  981. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  982. [self reloadDatasource:serverUrl];
  983. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  984. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  985. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView]];
  986. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  987. _docController.delegate = self;
  988. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  989. }
  990. // Save to Photo Album
  991. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  992. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  993. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  994. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  995. UIImage *image = [UIImage imageWithContentsOfFile:file];
  996. if (image)
  997. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  998. else
  999. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1000. }
  1001. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  1002. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView] error:nil];
  1003. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView])) {
  1004. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1005. } else {
  1006. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1007. }
  1008. }
  1009. if (status != PHAuthorizationStatusAuthorized) {
  1010. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1011. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  1012. [alertController addAction:okAction];
  1013. [self presentViewController:alertController animated:YES completion:nil];
  1014. }
  1015. [self reloadDatasource:serverUrl];
  1016. }
  1017. // Copy File
  1018. if ([selector isEqualToString:selectorLoadCopy]) {
  1019. [self reloadDatasource:serverUrl];
  1020. [self copyFileToPasteboard:metadata];
  1021. }
  1022. //selectorLoadViewImage
  1023. if ([selector isEqualToString:selectorLoadViewImage]) {
  1024. // Detail
  1025. if (app.activeDetail)
  1026. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1027. // Photos
  1028. if (app.activePhotos)
  1029. [app.activePhotos downloadFileSuccess:metadata];
  1030. [self reloadDatasource:serverUrl];
  1031. }
  1032. // if exists postselector call self with selectorPost
  1033. if ([selectorPost length] > 0)
  1034. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1035. // Auto Download Upload
  1036. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1037. // ONLY BACKGROUND
  1038. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1039. } else {
  1040. // ONLY FOREFROUND
  1041. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1042. }
  1043. }
  1044. - (void)downloadSelectedFilesFolders
  1045. {
  1046. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1047. return;
  1048. NSLog(@"[LOG] Start download selected ...");
  1049. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1050. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1051. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1052. for (tableMetadata *metadata in selectedMetadatas) {
  1053. if (metadata.directory) {
  1054. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1055. if (serverUrl) {
  1056. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1057. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1058. }
  1059. } else {
  1060. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1061. }
  1062. }
  1063. [_hud hideHud];
  1064. });
  1065. [self tableViewSelect:NO];
  1066. }
  1067. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1068. {
  1069. }
  1070. #pragma --------------------------------------------------------------------------------------------
  1071. #pragma mark ===== Upload new Photos/Videos =====
  1072. #pragma --------------------------------------------------------------------------------------------
  1073. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1074. {
  1075. // Auto Download Upload
  1076. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1077. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1078. // Change priority Auto Upload
  1079. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1080. // Activity
  1081. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1082. }
  1083. if (errorCode != kCFURLErrorCancelled)
  1084. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1085. } else {
  1086. // Delete record on Table Auto Upload
  1087. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1088. // Activity
  1089. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1090. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1091. }
  1092. } else {
  1093. // Read File test do not exists
  1094. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1095. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1096. // reUpload
  1097. if (metadata)
  1098. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1099. }
  1100. // Print error
  1101. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1102. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1103. }
  1104. }
  1105. [self reloadDatasource:serverUrl];
  1106. }
  1107. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1108. {
  1109. // Auto Download Upload
  1110. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1111. // ONLY BACKGROUND
  1112. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1113. } else {
  1114. // ONLY FOREFROUND
  1115. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1116. }
  1117. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1118. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1119. [self readFolder:serverUrl];
  1120. } else {
  1121. [self reloadDatasource:serverUrl];
  1122. }
  1123. });
  1124. }
  1125. //
  1126. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1127. //
  1128. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1129. {
  1130. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1131. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1132. });
  1133. }
  1134. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1135. {
  1136. NSArray *assets = [arguments objectAtIndex:0];
  1137. __block NSString *serverUrl = [arguments objectAtIndex:1];
  1138. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1139. NSString *session = [arguments objectAtIndex:3];
  1140. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1141. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1142. if (!directoryID) return;
  1143. // if request create the folder for Photos & the subfolders
  1144. if ([autoUploadPath isEqualToString:serverUrl])
  1145. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1146. return;
  1147. for (PHAsset *asset in assets) {
  1148. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1149. NSDate *assetDate = asset.creationDate;
  1150. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1151. // Create serverUrl if use sub folder
  1152. if (useSubFolder) {
  1153. [formatter setDateFormat:@"yyyy"];
  1154. NSString *yearString = [formatter stringFromDate:assetDate];
  1155. [formatter setDateFormat:@"MM"];
  1156. NSString *monthString = [formatter stringFromDate:assetDate];
  1157. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1158. }
  1159. // Check if is in upload
  1160. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1161. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1162. if ([isRecordInSessions count] > 0)
  1163. continue;
  1164. // Prepare record metadataNet
  1165. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1166. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1167. metadataNet.fileName = fileName;
  1168. metadataNet.session = session;
  1169. metadataNet.selector = selectorUploadFile;
  1170. metadataNet.selectorPost = nil;
  1171. metadataNet.serverUrl = serverUrl;
  1172. metadataNet.taskStatus = k_taskStatusResume;
  1173. // Check il file already exists
  1174. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileNameView = %@", app.activeAccount, directoryID, fileName]];
  1175. if (metadata) {
  1176. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1177. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1178. // NO OVERWITE
  1179. }];
  1180. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1181. // Send to Upload Queue
  1182. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1183. }];
  1184. [alertController addAction:cancelAction];
  1185. [alertController addAction:overwriteAction];
  1186. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  1187. alertWindow.rootViewController = [[UIViewController alloc]init];
  1188. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  1189. [alertWindow makeKeyAndVisible];
  1190. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  1191. } else {
  1192. // Send to Upload Queue
  1193. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1194. }
  1195. }
  1196. }
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. #pragma mark ==== Read File ====
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1201. {
  1202. // Unauthorized
  1203. if (errorCode == kOCErrorServerUnauthorized)
  1204. [app openLoginView:self loginType:loginModifyPasswordUser];
  1205. }
  1206. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1207. {
  1208. // Read Folder
  1209. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1210. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1211. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1212. [self readFolder:metadataNet.serverUrl];
  1213. }
  1214. }
  1215. }
  1216. - (void)readFileReloadFolder
  1217. {
  1218. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1219. return;
  1220. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1221. metadataNet.action = actionReadFile;
  1222. metadataNet.priority = NSOperationQueuePriorityHigh;
  1223. metadataNet.selector = selectorReadFileReloadFolder;
  1224. metadataNet.serverUrl = _serverUrl;
  1225. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1226. }
  1227. #pragma --------------------------------------------------------------------------------------------
  1228. #pragma mark ==== Read Folder ====
  1229. #pragma --------------------------------------------------------------------------------------------
  1230. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1231. {
  1232. // stoprefresh
  1233. [_refreshControl endRefreshing];
  1234. // Unauthorized
  1235. if (errorCode == kOCErrorServerUnauthorized)
  1236. [app openLoginView:self loginType:loginModifyPasswordUser];
  1237. _loadingFolder = NO;
  1238. [self tableViewReloadData];
  1239. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1240. // verify active user
  1241. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1242. if (message && [record.account isEqualToString:metadataNet.account])
  1243. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1244. [self reloadDatasource:metadataNet.serverUrl];
  1245. }
  1246. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1247. {
  1248. // stoprefresh
  1249. [_refreshControl endRefreshing];
  1250. // verify active user
  1251. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1252. if (![record.account isEqualToString:metadataNet.account])
  1253. return;
  1254. // save father e update permission
  1255. if(!_isSearchMode && metadataFolder)
  1256. _fatherPermission = metadataFolder.permissions;
  1257. NSArray *recordsInSessions;
  1258. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1259. if (_isSearchMode) {
  1260. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1261. } else {
  1262. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1263. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1264. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1265. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1266. }
  1267. for (tableMetadata *metadata in metadatas) {
  1268. // verify if the record is in download/upload progress
  1269. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1270. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1271. // is in Download or Upload
  1272. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1273. continue;
  1274. }
  1275. }
  1276. // Insert in Array
  1277. [metadatasToInsertInDB addObject:metadata];
  1278. }
  1279. // insert in Database
  1280. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1281. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1282. // read plist
  1283. if (!_isSearchMode)
  1284. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1285. // File is changed ??
  1286. if (!_isSearchMode && metadatasToInsertInDB)
  1287. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1288. });
  1289. // Search Mode
  1290. if (_isSearchMode) {
  1291. // Fix managed -> Unmanaged _searchResultMetadatas
  1292. if (metadatasToInsertInDB)
  1293. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1294. [self reloadDatasource:metadataNet.serverUrl];
  1295. }
  1296. // this is the same directory
  1297. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1298. // reload
  1299. [self reloadDatasource:metadataNet.serverUrl];
  1300. // Enable change user
  1301. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1302. _loadingFolder = NO;
  1303. [self tableViewReloadData];
  1304. }
  1305. // Is encrypted folder get metadata
  1306. if (metadataFolder.e2eEncrypted == true) {
  1307. if ([CCUtility isEndToEndEnabled:app.activeAccount]) {
  1308. [app.endToEndInterface getEndToEndMetadata:metadataFolder];
  1309. } else {
  1310. [app messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1311. }
  1312. }
  1313. }
  1314. - (void)readFolder:(NSString *)serverUrl
  1315. {
  1316. // init control
  1317. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1318. [_refreshControl endRefreshing];
  1319. return;
  1320. }
  1321. // Search Mode
  1322. if (_isSearchMode) {
  1323. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1324. _searchFileName = @""; // forced reload searchg
  1325. [self updateSearchResultsForSearchController:self.searchController];
  1326. return;
  1327. }
  1328. _loadingFolder = YES;
  1329. [self tableViewReloadData];
  1330. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1331. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1332. metadataNet.action = actionReadFolder;
  1333. metadataNet.date = [NSDate date];
  1334. metadataNet.depth = @"1";
  1335. metadataNet.directoryID = directory.directoryID;
  1336. metadataNet.priority = NSOperationQueuePriorityHigh;
  1337. metadataNet.selector = selectorReadFolder;
  1338. metadataNet.serverUrl = serverUrl;
  1339. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1340. }
  1341. #pragma mark -
  1342. #pragma --------------------------------------------------------------------------------------------
  1343. #pragma mark ===== Search =====
  1344. #pragma --------------------------------------------------------------------------------------------
  1345. - (void)searchEnabled:(BOOL)enabled
  1346. {
  1347. if (enabled) {
  1348. self.definesPresentationContext = YES;
  1349. self.searchController.searchResultsUpdater = self;
  1350. self.searchController.dimsBackgroundDuringPresentation = NO;
  1351. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  1352. [self.searchController.searchBar sizeToFit];
  1353. self.searchController.searchBar.delegate = self;
  1354. if (@available(iOS 11, *)) {
  1355. self.navigationItem.searchController = self.searchController;
  1356. self.navigationItem.hidesSearchBarWhenScrolling = true;
  1357. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  1358. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  1359. textField.textColor = [UIColor blackColor];
  1360. textField.tintColor = [UIColor blackColor];
  1361. UIView *backgroundView = textField.subviews.firstObject;
  1362. backgroundView.backgroundColor = UIColor.whiteColor;
  1363. backgroundView.layer.cornerRadius = 10;
  1364. backgroundView.clipsToBounds = YES;
  1365. } else {
  1366. self.tableView.tableHeaderView = self.searchController.searchBar;
  1367. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1368. }
  1369. } else {
  1370. if (@available(iOS 11, *)) {
  1371. self.navigationItem.searchController = nil;
  1372. } else {
  1373. self.tableView.tableHeaderView = nil;
  1374. }
  1375. }
  1376. }
  1377. - (void)searchStartTimer
  1378. {
  1379. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1380. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1381. _noFilesSearchTitle = @"";
  1382. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1383. [self.tableView reloadEmptyDataSet];
  1384. }
  1385. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1386. {
  1387. //[self setNeedsStatusBarAppearanceUpdate];
  1388. _isSearchMode = YES;
  1389. [self deleteRefreshControl];
  1390. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1391. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1392. _searchFileName = fileName;
  1393. // First : filter
  1394. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1395. if (!directoryID) return;
  1396. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileNameView CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1397. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1398. [_searchResultMetadatas removeAllObjects];
  1399. for (tableMetadata *record in records)
  1400. [_searchResultMetadatas addObject:record];
  1401. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1402. metadataNet.account = app.activeAccount;
  1403. metadataNet.directoryID = directoryID;
  1404. metadataNet.selector = selectorSearch;
  1405. metadataNet.serverUrl = _serverUrl;
  1406. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1407. // Version >= 12
  1408. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1409. [_timerWaitInput invalidate];
  1410. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1411. }
  1412. }
  1413. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1414. [self reloadDatasource];
  1415. }
  1416. }
  1417. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1418. {
  1419. [self cancelSearchBar];
  1420. [self readFolder:_serverUrl];
  1421. }
  1422. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1423. {
  1424. // Unauthorized
  1425. if (errorCode == kOCErrorServerUnauthorized)
  1426. [app openLoginView:self loginType:loginModifyPasswordUser];
  1427. if (message && errorCode != kOCErrorServerUnauthorized)
  1428. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1429. _searchFileName = @"";
  1430. }
  1431. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1432. {
  1433. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1434. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1435. }
  1436. - (void)cancelSearchBar
  1437. {
  1438. if (self.searchController.active) {
  1439. [self.searchController setActive:NO];
  1440. [self createRefreshControl];
  1441. _isSearchMode = NO;
  1442. _searchFileName = @"";
  1443. _dateReadDataSource = nil;
  1444. _searchResultMetadatas = [NSMutableArray new];
  1445. [self reloadDatasource];
  1446. }
  1447. //[self setNeedsStatusBarAppearanceUpdate];
  1448. }
  1449. #pragma mark -
  1450. #pragma --------------------------------------------------------------------------------------------
  1451. #pragma mark ===== Delete File or Folder =====
  1452. #pragma --------------------------------------------------------------------------------------------
  1453. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1454. {
  1455. // Unauthorized
  1456. if (errorCode == kOCErrorServerUnauthorized)
  1457. [app openLoginView:self loginType:loginModifyPasswordUser];
  1458. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1459. [self deleteFileOrFolderSuccess:metadataNet];
  1460. }
  1461. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1462. {
  1463. [_queueSelector removeObject:metadataNet.selector];
  1464. if ([_queueSelector count] == 0) {
  1465. [_hud hideHud];
  1466. // next
  1467. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1468. if ([_selectedFileIDsMetadatas count] > 0) {
  1469. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1470. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1471. } else {
  1472. // End Select Table View
  1473. [self tableViewSelect:NO];
  1474. // Reload
  1475. if (_isSearchMode)
  1476. [self readFolder:metadataNet.serverUrl];
  1477. else
  1478. [self reloadDatasource:metadataNet.serverUrl];
  1479. }
  1480. }
  1481. }
  1482. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1483. {
  1484. [_queueSelector addObject:selectorDelete];
  1485. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1486. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1487. }
  1488. - (void)deleteFile
  1489. {
  1490. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1491. return;
  1492. [_queueSelector removeAllObjects];
  1493. if ([_selectedFileIDsMetadatas count] > 0) {
  1494. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1495. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1496. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1497. } else {
  1498. _numSelectedFileIDsMetadatas = 1;
  1499. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1500. }
  1501. }
  1502. #pragma --------------------------------------------------------------------------------------------
  1503. #pragma mark ===== Rename / Move =====
  1504. #pragma --------------------------------------------------------------------------------------------
  1505. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1506. {
  1507. [self readFolder:metadataNet.serverUrl];
  1508. }
  1509. - (void)renameFile:(NSArray *)arguments
  1510. {
  1511. tableMetadata* metadata = [arguments objectAtIndex:0];
  1512. NSString *fileName = [arguments objectAtIndex:1];
  1513. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1514. }
  1515. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1516. {
  1517. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1518. [_hud hideHud];
  1519. if (message && errorCode != kOCErrorServerUnauthorized)
  1520. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1521. // End Select Table View
  1522. [self tableViewSelect:NO];
  1523. // reload Datasource
  1524. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1525. [self readFolder:metadataNet.serverUrl];
  1526. else
  1527. [self reloadDatasource];
  1528. }
  1529. }
  1530. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1531. {
  1532. [_queueSelector removeObject:metadataNet.selector];
  1533. if ([_queueSelector count] == 0) {
  1534. [_hud hideHud];
  1535. NSString *fileName = metadataNet.fileName;
  1536. NSString *directoryID = metadataNet.directoryID;
  1537. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1538. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1539. if (!serverUrlTo) return;
  1540. // FILE -> Metadata
  1541. if (metadataNet.directory == NO)
  1542. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1543. // DIRECTORY -> Directory - CCMetadata
  1544. if (metadataNet.directory == YES) {
  1545. // delete all dir / subdir
  1546. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1547. // move metadata
  1548. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1549. // Add new directory
  1550. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1551. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1552. }
  1553. // next
  1554. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1555. if ([_selectedFileIDsMetadatas count] > 0) {
  1556. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1557. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1558. } else {
  1559. // End Select Table View
  1560. [self tableViewSelect:NO];
  1561. // reload Datasource
  1562. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1563. [self readFolder:metadataNet.serverUrl];
  1564. else
  1565. [self reloadDatasource];
  1566. }
  1567. }
  1568. }
  1569. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1570. {
  1571. tableMetadata *metadata = [arguments objectAtIndex:0];
  1572. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1573. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1574. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1575. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1576. if (!serverUrl) return;
  1577. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1578. if (!directoryIDTo) return;
  1579. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1580. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1581. if(!error) {
  1582. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1583. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1584. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1585. }];
  1586. [alert addAction:ok];
  1587. [self presentViewController:alert animated:YES completion:nil];
  1588. });
  1589. // End Select Table View
  1590. [self tableViewSelect:NO];
  1591. // reload Datasource
  1592. [self readFileReloadFolder];
  1593. return;
  1594. }
  1595. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1596. metadataNet.action = actionMoveFileOrFolder;
  1597. metadataNet.directory = metadata.directory;
  1598. metadataNet.fileID = metadata.fileID;
  1599. metadataNet.directoryID = metadata.directoryID;
  1600. metadataNet.directoryIDTo = directoryIDTo;
  1601. metadataNet.fileName = metadata.fileName;
  1602. metadataNet.fileNameView = metadata.fileNameView;
  1603. metadataNet.fileNameTo = metadata.fileName;
  1604. metadataNet.etag = metadata.etag;
  1605. metadataNet.selector = selectorMove;
  1606. metadataNet.serverUrl = serverUrl;
  1607. metadataNet.serverUrlTo = serverUrlTo;
  1608. [_queueSelector addObject:metadataNet.selector];
  1609. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1610. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1611. }
  1612. // DELEGATE : Move
  1613. - (void)dismissMove
  1614. {
  1615. [self reloadDatasource];
  1616. }
  1617. // DELEGATE : Move
  1618. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1619. {
  1620. [_queueSelector removeAllObjects];
  1621. // DENIED e2e
  1622. if ([CCUtility isFolderEncrypted:serverUrlTo account:app.activeAccount]) {
  1623. [app messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1624. return;
  1625. }
  1626. if ([_selectedFileIDsMetadatas count] > 0) {
  1627. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1628. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1629. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1630. } else {
  1631. _numSelectedFileIDsMetadatas = 1;
  1632. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1633. }
  1634. }
  1635. - (void)moveOpenWindow:(NSArray *)indexPaths
  1636. {
  1637. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1638. return;
  1639. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1640. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1641. viewController.delegate = self;
  1642. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1643. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1644. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1645. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1646. viewController.networkingOperationQueue = app.netQueue;
  1647. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1648. [self presentViewController:navigationController animated:YES completion:nil];
  1649. }
  1650. #pragma --------------------------------------------------------------------------------------------
  1651. #pragma mark ===== Create folder =====
  1652. #pragma --------------------------------------------------------------------------------------------
  1653. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1654. {
  1655. // Unauthorized
  1656. if (errorCode == kOCErrorServerUnauthorized)
  1657. [app openLoginView:self loginType:loginModifyPasswordUser];
  1658. if (message && errorCode != kOCErrorServerUnauthorized)
  1659. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1660. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1661. [self reloadDatasource];
  1662. // We are in directory fail ?
  1663. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1664. if (vc)
  1665. [vc.navigationController popViewControllerAnimated:YES];
  1666. }
  1667. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1668. {
  1669. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1670. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1671. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1672. if (metadata) {
  1673. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1674. metadata.fileID = metadataNet.fileID;
  1675. metadata.date = metadataNet.date;
  1676. metadata.permissions = @"RDNVCK";
  1677. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1678. [self reloadDatasource];
  1679. } else {
  1680. [self readFileReloadFolder];
  1681. }
  1682. }
  1683. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1684. {
  1685. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1686. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1687. if (![fileNameFolder length]) return;
  1688. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1689. if (!directoryID) return;
  1690. metadataNet.action = actionCreateFolder;
  1691. metadataNet.directoryID = directoryID;
  1692. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1693. metadataNet.fileName = fileNameFolder;
  1694. metadataNet.selector = selectorCreateFolder;
  1695. metadataNet.serverUrl = serverUrl;
  1696. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1697. // Create Directory on metadata
  1698. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1699. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1700. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1701. [self reloadDatasource];
  1702. }
  1703. #pragma --------------------------------------------------------------------------------------------
  1704. #pragma mark ===== Progress & Task Button =====
  1705. #pragma --------------------------------------------------------------------------------------------
  1706. - (void)triggerProgressTask:(NSNotification *)notification
  1707. {
  1708. NSDictionary *dict = notification.userInfo;
  1709. NSString *fileID = [dict valueForKey:@"fileID"];
  1710. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1711. float progress = [[dict valueForKey:@"progress"] floatValue];
  1712. // Check
  1713. if (!fileID || [fileID isEqualToString: @""])
  1714. return;
  1715. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1716. if (![serverUrl isEqualToString:_serverUrl])
  1717. return;
  1718. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1719. if ([self indexPathIsValid:indexPath]) {
  1720. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1721. cell.progressView.progressTintColor = [UIColor blackColor];
  1722. cell.progressView.hidden = NO;
  1723. [cell.progressView setProgress:progress];
  1724. }
  1725. }
  1726. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1727. {
  1728. UITouch * touch = [[event allTouches] anyObject];
  1729. CGPoint location = [touch locationInView:self.tableView];
  1730. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1731. if ([self indexPathIsValid:indexPath]) {
  1732. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1733. if (metadataSection) {
  1734. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1735. if (metadata)
  1736. [self reloadTaskButton:metadata];
  1737. }
  1738. }
  1739. }
  1740. - (void)reloadTaskButton:(tableMetadata *)metadata
  1741. {
  1742. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1743. __block NSURLSessionTask *findTask;
  1744. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1745. NSString *fileID = metadata.fileID;
  1746. // DOWNLOAD
  1747. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1748. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1749. for (NSURLSessionUploadTask *task in downloadTasks)
  1750. if (task.taskIdentifier == sessionTaskIdentifier) {
  1751. findTask = task;
  1752. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1753. [task cancel];
  1754. }
  1755. if (!findTask) {
  1756. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1757. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1758. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1759. }
  1760. }];
  1761. }
  1762. // UPLOAD
  1763. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1764. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1765. for (NSURLSessionUploadTask *task in uploadTasks)
  1766. if (task.taskIdentifier == sessionTaskIdentifier) {
  1767. findTask = task;
  1768. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1769. [task cancel];
  1770. }
  1771. if (!findTask) {
  1772. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1773. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1774. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1775. }
  1776. }];
  1777. }
  1778. }
  1779. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1780. {
  1781. UITouch * touch = [[event allTouches] anyObject];
  1782. CGPoint location = [touch locationInView:self.tableView];
  1783. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1784. if ([self indexPathIsValid:indexPath]) {
  1785. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1786. if (metadataSection) {
  1787. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1788. if (metadata)
  1789. [self cancelTaskButton:metadata reloadTable:YES];
  1790. }
  1791. }
  1792. }
  1793. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1794. {
  1795. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1796. __block NSURLSessionTask *findTask;
  1797. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1798. NSString *fileID = metadata.fileID;
  1799. // DOWNLOAD
  1800. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1801. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1802. for (NSURLSessionTask *task in downloadTasks)
  1803. if (task.taskIdentifier == sessionTaskIdentifier) {
  1804. findTask = task;
  1805. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1806. [task cancel];
  1807. }
  1808. if (!findTask) {
  1809. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1810. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1811. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1812. }
  1813. }];
  1814. }
  1815. // UPLOAD
  1816. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1817. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1818. for (NSURLSessionUploadTask *task in uploadTasks)
  1819. if (task.taskIdentifier == sessionTaskIdentifier) {
  1820. findTask = task;
  1821. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1822. [task cancel];
  1823. }
  1824. if (!findTask) {
  1825. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1826. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1827. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1828. }
  1829. }];
  1830. }
  1831. }
  1832. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1833. {
  1834. UITouch * touch = [[event allTouches] anyObject];
  1835. CGPoint location = [touch locationInView:self.tableView];
  1836. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1837. if ([self indexPathIsValid:indexPath]) {
  1838. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1839. if (metadataSection) {
  1840. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1841. if (metadata)
  1842. [self stopTaskButton:metadata];
  1843. }
  1844. }
  1845. }
  1846. - (void)stopTaskButton:(tableMetadata *)metadata
  1847. {
  1848. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1849. __block NSURLSessionTask *findTask;
  1850. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1851. NSString *fileID = metadata.fileID;
  1852. // UPLOAD
  1853. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1854. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1855. for (NSURLSessionUploadTask *task in uploadTasks)
  1856. if (task.taskIdentifier == sessionTaskIdentifier) {
  1857. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1858. findTask = task;
  1859. [task cancel];
  1860. }
  1861. if (!findTask) {
  1862. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1863. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1864. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1865. }
  1866. }];
  1867. }
  1868. }
  1869. #pragma --------------------------------------------------------------------------------------------
  1870. #pragma mark ===== Shared =====
  1871. #pragma --------------------------------------------------------------------------------------------
  1872. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1873. {
  1874. [_hud hideHud];
  1875. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1876. // change account ?
  1877. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1878. if([record.account isEqualToString:metadataNet.account] == NO)
  1879. return;
  1880. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1881. if (result) {
  1882. appDelegate.sharesLink = result[0];
  1883. appDelegate.sharesUserAndGroup = result[1];
  1884. }
  1885. // Notify Shares View
  1886. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1887. if (openWindow) {
  1888. if (_shareOC) {
  1889. [_shareOC reloadData];
  1890. } else {
  1891. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1892. // Apriamo la view
  1893. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1894. _shareOC.delegate = self;
  1895. _shareOC.metadata = metadata;
  1896. _shareOC.serverUrl = metadataNet.serverUrl;
  1897. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  1898. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  1899. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1900. [self presentViewController:_shareOC animated:YES completion:nil];
  1901. }
  1902. }
  1903. [self tableViewReloadData];
  1904. }
  1905. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1906. {
  1907. [_hud hideHud];
  1908. // Unauthorized
  1909. if (errorCode == kOCErrorServerUnauthorized)
  1910. [app openLoginView:self loginType:loginModifyPasswordUser];
  1911. if (errorCode != kOCErrorServerUnauthorized)
  1912. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1913. if (_shareOC)
  1914. [_shareOC reloadData];
  1915. [self tableViewReloadData];
  1916. }
  1917. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1918. {
  1919. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1920. metadataNet.action = actionShare;
  1921. metadataNet.fileID = metadata.fileID;
  1922. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  1923. metadataNet.fileNameView = metadata.fileNameView;
  1924. metadataNet.password = password;
  1925. metadataNet.selector = selectorShare;
  1926. metadataNet.serverUrl = serverUrl;
  1927. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1928. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1929. }
  1930. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1931. {
  1932. [_hud hideHud];
  1933. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  1934. // rimuoviamo la condivisione da db
  1935. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1936. if (result) {
  1937. appDelegate.sharesLink = result[0];
  1938. appDelegate.sharesUserAndGroup = result[1];
  1939. }
  1940. if (_shareOC)
  1941. [_shareOC reloadData];
  1942. [self tableViewReloadData];
  1943. }
  1944. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1945. {
  1946. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1947. metadataNet.action = actionUnShare;
  1948. metadataNet.fileID = metadata.fileID;
  1949. metadataNet.fileName = metadata.fileName;
  1950. metadataNet.fileNameView = metadata.fileNameView;
  1951. metadataNet.selector = selectorUnshare;
  1952. metadataNet.serverUrl = serverUrl;
  1953. metadataNet.share = share;
  1954. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1955. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1956. }
  1957. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1958. {
  1959. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1960. metadataNet.action = actionUpdateShare;
  1961. metadataNet.fileID = metadata.fileID;
  1962. metadataNet.expirationTime = expirationTime;
  1963. metadataNet.password = password;
  1964. metadataNet.selector = selectorUpdateShare;
  1965. metadataNet.serverUrl = serverUrl;
  1966. metadataNet.share = share;
  1967. metadataNet.sharePermission = permission;
  1968. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1969. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1970. }
  1971. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1972. {
  1973. [_hud hideHud];
  1974. if (_shareOC)
  1975. [_shareOC reloadUserAndGroup:items];
  1976. }
  1977. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1978. {
  1979. [_hud hideHud];
  1980. // Unauthorized
  1981. if (errorCode == kOCErrorServerUnauthorized)
  1982. [app openLoginView:self loginType:loginModifyPasswordUser];
  1983. if (errorCode != kOCErrorServerUnauthorized)
  1984. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1985. }
  1986. - (void)getUserAndGroup:(NSString *)find
  1987. {
  1988. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1989. metadataNet.action = actionGetUserAndGroup;
  1990. metadataNet.options = find;
  1991. metadataNet.selector = selectorGetUserAndGroup;
  1992. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1993. [_hud visibleIndeterminateHud];
  1994. }
  1995. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1996. {
  1997. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1998. metadataNet.action = actionShareWith;
  1999. metadataNet.fileID = metadata.fileID;
  2000. metadataNet.directoryID = directoryID;
  2001. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2002. metadataNet.fileNameView = metadata.fileNameView;
  2003. metadataNet.serverUrl = serverUrl;
  2004. metadataNet.selector = selectorShare;
  2005. metadataNet.share = user;
  2006. metadataNet.shareeType = shareeType;
  2007. metadataNet.sharePermission = permission;
  2008. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2009. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2010. }
  2011. - (void)openWindowShare:(tableMetadata *)metadata
  2012. {
  2013. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2014. if (!serverUrl) return;
  2015. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2016. metadataNet.action = actionReadShareServer;
  2017. metadataNet.fileID = metadata.fileID;
  2018. metadataNet.fileName = metadata.fileName;
  2019. metadataNet.fileNameView = metadata.fileNameView;
  2020. metadataNet.selector = selectorOpenWindowShare;
  2021. metadataNet.serverUrl = serverUrl;
  2022. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2023. [_hud visibleIndeterminateHud];
  2024. }
  2025. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2026. {
  2027. CGPoint location = [tapGesture locationInView:self.tableView];
  2028. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2029. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2030. if (metadata)
  2031. [self openWindowShare:metadata];
  2032. }
  2033. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2034. {
  2035. CGPoint location = [tapGesture locationInView:self.tableView];
  2036. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2037. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2038. if (metadata) {
  2039. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2040. vc.metadata = metadata;
  2041. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2042. [self presentViewController:vc animated:YES completion:nil];
  2043. }
  2044. }
  2045. #pragma --------------------------------------------------------------------------------------------
  2046. #pragma mark ===== Favorite =====
  2047. #pragma --------------------------------------------------------------------------------------------
  2048. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2049. {
  2050. _dateReadDataSource = nil;
  2051. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2052. if (_isSearchMode)
  2053. [self readFolder:metadataNet.serverUrl];
  2054. else
  2055. [self reloadDatasource:metadataNet.serverUrl];
  2056. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2057. if (metadata.directory && metadata.favorite) {
  2058. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2059. [app.activeFavorites addFavoriteFolder:dir];
  2060. }
  2061. }
  2062. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2063. {
  2064. // Unauthorized
  2065. if (errorCode == kOCErrorServerUnauthorized)
  2066. [app openLoginView:self loginType:loginModifyPasswordUser];
  2067. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2068. }
  2069. - (void)addFavorite:(tableMetadata *)metadata
  2070. {
  2071. if (metadata.directory) {
  2072. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2073. } else {
  2074. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2075. if (serverUrl)
  2076. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2077. }
  2078. }
  2079. - (void)removeFavorite:(tableMetadata *)metadata
  2080. {
  2081. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2082. }
  2083. #pragma --------------------------------------------------------------------------------------------
  2084. #pragma mark ===== Open in... =====
  2085. #pragma --------------------------------------------------------------------------------------------
  2086. - (void)openIn:(tableMetadata *)metadata
  2087. {
  2088. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2089. if (!serverUrl) return;
  2090. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2091. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2092. if ([self indexPathIsValid:indexPath])
  2093. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2094. }
  2095. #pragma --------------------------------------------------------------------------------------------
  2096. #pragma mark ===== Remove Local File =====
  2097. #pragma --------------------------------------------------------------------------------------------
  2098. - (void)removeLocalFile:(tableMetadata *)metadata
  2099. {
  2100. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2101. if (!serverUrl) return;
  2102. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2103. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2104. [self reloadDatasource:serverUrl];
  2105. }
  2106. #pragma --------------------------------------------------------------------------------------------
  2107. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2108. #pragma --------------------------------------------------------------------------------------------
  2109. - (void)orderTable:(NSString *)order
  2110. {
  2111. [CCUtility setOrderSettings:order];
  2112. // Clear data-read of DataSource
  2113. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2114. }
  2115. - (void)ascendingTable:(BOOL)ascending
  2116. {
  2117. [CCUtility setAscendingSettings:ascending];
  2118. // Clear data-read of DataSource
  2119. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2120. }
  2121. - (void)directoryOnTop:(BOOL)directoryOnTop
  2122. {
  2123. [CCUtility setDirectoryOnTop:directoryOnTop];
  2124. // Clear data-read of DataSource
  2125. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2126. }
  2127. - (void)tableGroupBy:(NSString *)groupBy
  2128. {
  2129. [CCUtility setGroupBySettings:groupBy];
  2130. // Clear data-read of DataSource
  2131. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2132. }
  2133. #pragma --------------------------------------------------------------------------------------------
  2134. #pragma mark ==== Menu LOGO ====
  2135. #pragma --------------------------------------------------------------------------------------------
  2136. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2137. {
  2138. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2139. return;
  2140. // Brand
  2141. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2142. return;
  2143. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2144. NSUInteger numInQueue = [app.netQueue operationCount];
  2145. if (numInSession+numInQueue > 0) {
  2146. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2147. return;
  2148. }
  2149. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2150. NSMutableArray *menuArray = [NSMutableArray new];
  2151. for (NSString *account in listAccount) {
  2152. if ([account isEqualToString:app.activeAccount]) continue;
  2153. CCMenuItem *item = [[CCMenuItem alloc] init];
  2154. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2155. item.argument = account;
  2156. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2157. item.target = self;
  2158. item.action = @selector(changeDefaultAccount:);
  2159. [menuArray addObject:item];
  2160. }
  2161. if ([menuArray count] == 0)
  2162. return;
  2163. OptionalConfiguration options;
  2164. Color textColor, backgroundColor;
  2165. textColor.R = 0;
  2166. textColor.G = 0;
  2167. textColor.B = 0;
  2168. backgroundColor.R = 1;
  2169. backgroundColor.G = 1;
  2170. backgroundColor.B = 1;
  2171. options.arrowSize = 9;
  2172. options.marginXSpacing = 7;
  2173. options.marginYSpacing = 10;
  2174. options.intervalSpacing = 20;
  2175. options.menuCornerRadius = 6.5;
  2176. options.maskToBackground = NO;
  2177. options.shadowOfMenu = YES;
  2178. options.hasSeperatorLine = YES;
  2179. options.seperatorLineHasInsets = YES;
  2180. options.textColor = textColor;
  2181. options.menuBackgroundColor = backgroundColor;
  2182. CGRect rect = self.view.frame;
  2183. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2184. CGFloat safeAreaTop = 0;
  2185. CGFloat offsetY = 35;
  2186. if (@available(iOS 11, *)) {
  2187. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2188. }
  2189. rect.origin.y = locationY + safeAreaTop + offsetY;
  2190. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2191. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2192. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2193. }
  2194. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2195. {
  2196. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2197. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2198. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2199. if (tableAccount) {
  2200. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2201. // go to home sweet home
  2202. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2203. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2204. }
  2205. });
  2206. }
  2207. #pragma --------------------------------------------------------------------------------------------
  2208. #pragma mark ==== ReMenu ====
  2209. #pragma --------------------------------------------------------------------------------------------
  2210. - (void)createReMenuBackgroundView:(REMenu *)menu
  2211. {
  2212. CGFloat safeAreaBottom = 0;
  2213. CGFloat safeAreaTop = 0;
  2214. CGFloat statusBar = 0;
  2215. if (@available(iOS 11, *)) {
  2216. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2217. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2218. }
  2219. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2220. statusBar = 13;
  2221. }
  2222. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2223. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2224. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2225. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2226. [UIView animateWithDuration:0.2 animations:^{
  2227. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2228. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2229. if (y>minimum) {
  2230. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2231. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2232. }
  2233. }];
  2234. }
  2235. - (void)createReMainMenu
  2236. {
  2237. NSString *ordinamento;
  2238. NSString *groupBy = _directoryGroupBy;
  2239. __block NSString *nuovoOrdinamento;
  2240. NSString *titoloNuovo, *titoloAttuale;
  2241. BOOL ascendente;
  2242. __block BOOL nuovoAscendente;
  2243. UIImage *image;
  2244. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2245. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2246. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2247. [self tableViewSelect:YES];
  2248. }
  2249. }];
  2250. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2251. ordinamento = _directoryOrder;
  2252. if ([ordinamento isEqualToString:@"fileName"]) {
  2253. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2254. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2255. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2256. nuovoOrdinamento = @"date";
  2257. }
  2258. if ([ordinamento isEqualToString:@"date"]) {
  2259. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2260. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2261. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2262. nuovoOrdinamento = @"fileName";
  2263. }
  2264. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2265. [self orderTable:nuovoOrdinamento];
  2266. }];
  2267. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2268. ascendente = [CCUtility getAscendingSettings];
  2269. if (ascendente) {
  2270. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2271. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2272. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2273. nuovoAscendente = false;
  2274. }
  2275. if (!ascendente) {
  2276. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2277. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2278. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2279. nuovoAscendente = true;
  2280. }
  2281. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2282. [self ascendingTable:nuovoAscendente];
  2283. }];
  2284. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2285. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2286. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2287. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2288. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2289. else [self tableGroupBy:@"alphabetic"];
  2290. }];
  2291. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2292. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2293. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2294. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2295. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2296. else [self tableGroupBy:@"typefile"];
  2297. }];
  2298. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2299. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2300. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2301. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2302. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2303. else [self tableGroupBy:@"date"];
  2304. }];
  2305. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2306. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2307. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2308. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2309. if ([CCUtility getDirectoryOnTop])
  2310. [self directoryOnTop:NO];
  2311. else
  2312. [self directoryOnTop:YES];
  2313. }];
  2314. // REMENU --------------------------------------------------------------------------------------------------------------
  2315. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2316. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2317. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2318. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2319. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2320. app.reMainMenu.separatorHeight = 0.5;
  2321. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2322. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2323. app.reMainMenu.textColor = [UIColor blackColor];
  2324. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2325. app.reMainMenu.textShadowColor = nil;
  2326. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2327. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2328. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2329. app.reMainMenu.highlightedSeparatorColor = nil;
  2330. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2331. app.reMainMenu.highlightedTextShadowColor = nil;
  2332. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2333. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2334. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2335. app.reMainMenu.subtitleTextShadowColor = nil;
  2336. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2337. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2338. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2339. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2340. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2341. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2342. app.reMainMenu.borderWidth = 0.3;
  2343. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2344. app.reMainMenu.animationDuration = 0.2;
  2345. app.reMainMenu.closeAnimationDuration = 0.2;
  2346. app.reMainMenu.bounce = NO;
  2347. [app.reMainMenu setClosePreparationBlock:^{
  2348. // Backgroun reMenu (Gesture)
  2349. [_reMenuBackgroundView removeFromSuperview];
  2350. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2351. }];
  2352. }
  2353. - (void)toggleReMainMenu
  2354. {
  2355. if (app.reMainMenu.isOpen) {
  2356. [app.reMainMenu close];
  2357. } else {
  2358. [self createReMainMenu];
  2359. [app.reMainMenu showFromNavigationController:self.navigationController];
  2360. // Backgroun reMenu & (Gesture)
  2361. [self createReMenuBackgroundView:app.reMainMenu];
  2362. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2363. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2364. }
  2365. }
  2366. - (void)createReSelectMenu
  2367. {
  2368. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2369. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2370. [self deleteFile];
  2371. }];
  2372. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2373. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2374. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2375. }];
  2376. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2377. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2378. [self downloadSelectedFilesFolders];
  2379. }];
  2380. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2381. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2382. [self saveSelectedFiles];
  2383. }];
  2384. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2385. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2386. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2387. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2388. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2389. app.reSelectMenu.separatorHeight = 0.5;
  2390. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2391. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2392. app.reSelectMenu.textColor = [UIColor blackColor];
  2393. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2394. app.reSelectMenu.textShadowColor = nil;
  2395. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2396. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2397. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2398. app.reSelectMenu.highlightedSeparatorColor = nil;
  2399. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2400. app.reSelectMenu.highlightedTextShadowColor = nil;
  2401. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2402. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2403. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2404. app.reSelectMenu.subtitleTextShadowColor = nil;
  2405. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2406. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2407. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2408. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2409. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2410. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2411. app.reSelectMenu.borderWidth = 0.3;
  2412. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2413. app.reSelectMenu.closeAnimationDuration = 0.2;
  2414. app.reSelectMenu.animationDuration = 0.2;
  2415. app.reSelectMenu.bounce = NO;
  2416. [app.reSelectMenu setClosePreparationBlock:^{
  2417. // Backgroun reMenu (Gesture)
  2418. [_reMenuBackgroundView removeFromSuperview];
  2419. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2420. }];
  2421. }
  2422. - (void)toggleReSelectMenu
  2423. {
  2424. if (app.reSelectMenu.isOpen) {
  2425. [app.reSelectMenu close];
  2426. } else {
  2427. [self createReSelectMenu];
  2428. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2429. // Backgroun reMenu & (Gesture)
  2430. [self createReMenuBackgroundView:app.reSelectMenu];
  2431. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2432. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2433. }
  2434. }
  2435. #pragma --------------------------------------------------------------------------------------------
  2436. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2437. #pragma --------------------------------------------------------------------------------------------
  2438. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2439. {
  2440. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2441. UITableView *tableView = (UITableView*)self.view;
  2442. CGPoint touchPoint = [recognizer locationInView:self.view];
  2443. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2444. if ([self indexPathIsValid:indexPath])
  2445. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2446. else
  2447. _metadata = nil;
  2448. [self becomeFirstResponder];
  2449. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2450. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2451. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2452. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2453. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2454. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2455. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2456. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2457. [menuController setMenuVisible:YES animated:YES];
  2458. }
  2459. }
  2460. - (BOOL)canBecomeFirstResponder
  2461. {
  2462. return YES;
  2463. }
  2464. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2465. {
  2466. // For copy file, copy files, Open in ... :
  2467. //
  2468. // NO Directory
  2469. // NO Error Passcode
  2470. // NO In Session mode (download/upload)
  2471. // NO Template
  2472. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2473. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2474. else return NO;
  2475. }
  2476. if (@selector(copyFiles:) == action) {
  2477. if (_isSelectedMode) {
  2478. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2479. for (tableMetadata *metadata in selectedMetadatas) {
  2480. if (!metadata.directory && metadata.session.length == 0)
  2481. return YES;
  2482. }
  2483. }
  2484. return NO;
  2485. }
  2486. if (@selector(pasteFile:) == action) {
  2487. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2488. NSArray *items = [pasteboard items];
  2489. if ([items count] == 1) {
  2490. // Value : (NSData) fileID
  2491. NSDictionary *dic = [items objectAtIndex:0];
  2492. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2493. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2494. if (fileID) {
  2495. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2496. if (metadata) {
  2497. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2498. if (account) {
  2499. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2500. if (directoryUser)
  2501. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2502. return YES;
  2503. }
  2504. }
  2505. }
  2506. }
  2507. return NO;
  2508. }
  2509. if (@selector(pasteFiles:) == action) {
  2510. BOOL isValid = NO;
  2511. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2512. NSArray *items = [pasteboard items];
  2513. if ([items count] <= 1) return NO;
  2514. for (NSDictionary *dic in items) {
  2515. // Value : (NSData) fileID
  2516. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2517. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2518. if (fileID) {
  2519. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2520. if (metadata) {
  2521. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2522. if (account) {
  2523. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2524. if (directoryUser) {
  2525. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2526. isValid = YES;
  2527. } else {
  2528. isValid = NO;
  2529. break;
  2530. }
  2531. } else {
  2532. isValid = NO;
  2533. break;
  2534. }
  2535. } else {
  2536. isValid = NO;
  2537. break;
  2538. }
  2539. } else {
  2540. isValid = NO;
  2541. break;
  2542. }
  2543. } else {
  2544. isValid = NO;
  2545. break;
  2546. }
  2547. }
  2548. return isValid;
  2549. }
  2550. return NO;
  2551. }
  2552. /************************************ COPY ************************************/
  2553. - (void)copyFile:(id)sender
  2554. {
  2555. // Remove all item
  2556. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2557. pasteboard.items = [[NSArray alloc] init];
  2558. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2559. [self copyFileToPasteboard:_metadata];
  2560. } else {
  2561. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2562. if (serverUrl)
  2563. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2564. }
  2565. }
  2566. - (void)copyFiles:(id)sender
  2567. {
  2568. // Remove all item
  2569. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2570. pasteboard.items = [[NSArray alloc] init];
  2571. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2572. for (tableMetadata *metadata in selectedMetadatas) {
  2573. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2574. [self copyFileToPasteboard:metadata];
  2575. } else {
  2576. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2577. if (serverUrl)
  2578. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2579. }
  2580. }
  2581. [self tableViewSelect:NO];
  2582. }
  2583. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2584. {
  2585. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2586. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2587. // Value : (NSData) fileID
  2588. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2589. [items addObject:item];
  2590. [pasteboard setItems:items];
  2591. }
  2592. /************************************ OPEN IN ... ******************************/
  2593. - (void)openinFile:(id)sender
  2594. {
  2595. [self openIn:_metadata];
  2596. }
  2597. /************************************ PASTE ************************************/
  2598. - (void)pasteFile:(id)sender
  2599. {
  2600. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2601. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2602. }
  2603. - (void)pasteFiles:(id)sender
  2604. {
  2605. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2606. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2607. }
  2608. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2609. {
  2610. float timer = 0;
  2611. for (NSDictionary *dic in items) {
  2612. // Value : (NSData) fileID
  2613. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2614. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2615. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2616. if (metadata) {
  2617. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2618. if (account) {
  2619. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2620. if (directoryUser) {
  2621. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2622. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNameView]];
  2623. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2624. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2625. });
  2626. timer += 0.1;
  2627. }
  2628. }
  2629. }
  2630. }
  2631. }
  2632. }
  2633. #pragma --------------------------------------------------------------------------------------------
  2634. #pragma mark ===== Lock Passcode =====
  2635. #pragma --------------------------------------------------------------------------------------------
  2636. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2637. {
  2638. return _failedAttempts;
  2639. }
  2640. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2641. {
  2642. return _lockUntilDate;
  2643. }
  2644. - (void)passcodeViewCloseButtonPressed:(id)sender
  2645. {
  2646. [self dismissViewControllerAnimated:YES completion:nil];
  2647. }
  2648. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2649. {
  2650. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2651. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2652. _lockUntilDate = nil;
  2653. _failedAttempts = 0;
  2654. aResultHandler(YES);
  2655. } else aResultHandler(NO);
  2656. } else aResultHandler(YES);
  2657. }
  2658. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2659. {
  2660. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2661. switch (aViewController.type) {
  2662. case BKPasscodeViewControllerCheckPasscodeType: {
  2663. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2664. // possiamo procedere alla prossima directory
  2665. [self performSegueDirectoryWithControlPasscode:false];
  2666. // avviamo la sessione Passcode Lock con now
  2667. app.sessionePasscodeLock = [NSDate date];
  2668. }
  2669. // disattivazione lock cartella
  2670. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2671. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2672. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2673. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2674. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2675. }
  2676. [self tableViewReloadData];
  2677. }
  2678. }
  2679. break;
  2680. default:
  2681. break;
  2682. }
  2683. }
  2684. - (void)comandoLockPassword
  2685. {
  2686. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2687. if (!serverUrl) return;
  2688. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2689. // se non è abilitato il Lock Passcode esci
  2690. if ([[CCUtility getBlockCode] length] == 0) {
  2691. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2692. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2693. [alertController addAction:okAction];
  2694. [self presentViewController:alertController animated:YES completion:nil];
  2695. return;
  2696. }
  2697. // se è richiesta la disattivazione si chiede la password
  2698. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2699. if (directory.lock) {
  2700. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2701. viewController.delegate = self;
  2702. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2703. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2704. viewController.inputViewTitlePassword = YES;
  2705. if ([CCUtility getSimplyBlockCode]) {
  2706. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2707. viewController.passcodeInputView.maximumLength = 6;
  2708. } else {
  2709. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2710. viewController.passcodeInputView.maximumLength = 64;
  2711. }
  2712. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2713. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2714. viewController.touchIDManager = touchIDManager;
  2715. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2716. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2717. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2718. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2719. [self presentViewController:navigationController animated:YES completion:nil];
  2720. return;
  2721. }
  2722. // ---------------- ACTIVATE PASSWORD
  2723. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2724. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2725. if ([self indexPathIsValid:indexPath])
  2726. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2727. } else {
  2728. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2729. }
  2730. }
  2731. #pragma mark -
  2732. #pragma --------------------------------------------------------------------------------------------
  2733. #pragma mark ===== Swipe Tablet -> menu =====
  2734. #pragma --------------------------------------------------------------------------------------------
  2735. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2736. {
  2737. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2738. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2739. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2740. return NO;
  2741. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2742. return NO;
  2743. else
  2744. return YES;
  2745. }
  2746. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2747. {
  2748. }
  2749. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2750. {
  2751. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2752. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2753. if (direction == MGSwipeDirectionRightToLeft) {
  2754. // Delete
  2755. if (index == 0)
  2756. [self swipeDelete:indexPath];
  2757. // More
  2758. if (index == 1)
  2759. [self swipeMore:indexPath];
  2760. }
  2761. if (direction == MGSwipeDirectionLeftToRight) {
  2762. if (_metadata.favorite)
  2763. [self removeFavorite:_metadata];
  2764. else
  2765. [self addFavorite:_metadata];
  2766. }
  2767. return YES;
  2768. }
  2769. - (void)swipeDelete:(NSIndexPath *)indexPath
  2770. {
  2771. // Directory locked ?
  2772. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2773. if (!lockServerUrl) return;
  2774. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2775. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2776. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2777. return;
  2778. }
  2779. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2780. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2781. [self performSelector:@selector(deleteFile) withObject:nil];
  2782. }]];
  2783. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2784. [alertController dismissViewControllerAnimated:YES completion:nil];
  2785. }]];
  2786. alertController.popoverPresentationController.sourceView = self.view;
  2787. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2788. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2789. [alertController.view layoutIfNeeded];
  2790. [self presentViewController:alertController animated:YES completion:nil];
  2791. }
  2792. - (void)swipeMore:(NSIndexPath *)indexPath
  2793. {
  2794. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2795. if (!serverUrl) return;
  2796. NSString *titoloLock, *titleFavorite;
  2797. if (_metadata.favorite) {
  2798. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2799. } else {
  2800. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2801. }
  2802. if (_metadata.directory) {
  2803. // calcolo lockServerUrl
  2804. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2805. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2806. if (directory.lock)
  2807. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2808. else
  2809. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2810. }
  2811. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2812. // ******************************************* AHKActionSheet *******************************************
  2813. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2814. actionSheet.animationDuration = 0.2;
  2815. actionSheet.buttonHeight = 50.0;
  2816. actionSheet.cancelButtonHeight = 50.0f;
  2817. actionSheet.separatorHeight = 5.0f;
  2818. actionSheet.automaticallyTintButtonImages = @(NO);
  2819. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2820. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2821. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2822. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2823. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2824. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2825. // ******************************************* DIRECTORY *******************************************
  2826. if (_metadata.directory) {
  2827. BOOL lockDirectory = NO;
  2828. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2829. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:app.activeAccount];
  2830. // Directory bloccata ?
  2831. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2832. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2833. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2834. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brand]
  2835. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2836. height:50.0
  2837. type:AHKActionSheetButtonTypeDisabled
  2838. handler:nil
  2839. ];
  2840. if (!lockDirectory && !isFolderEncrypted) {
  2841. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2842. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  2843. backgroundColor:[UIColor whiteColor]
  2844. height:50.0
  2845. type:AHKActionSheetButtonTypeDefault
  2846. handler:^(AHKActionSheet *as) {
  2847. [self openWindowShare:_metadata];
  2848. }];
  2849. }
  2850. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory) {
  2851. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2852. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2853. backgroundColor:[UIColor whiteColor]
  2854. height:50.0
  2855. type:AHKActionSheetButtonTypeDefault
  2856. handler:^(AHKActionSheet *as) {
  2857. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2858. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2859. textField.text = _metadata.fileNameView;
  2860. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2861. //textField.delegate = self;
  2862. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2863. }];
  2864. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2865. NSLog(@"[LOG] Cancel action");
  2866. }];
  2867. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2868. UITextField *fileName = alertController.textFields.firstObject;
  2869. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2870. }];
  2871. okAction.enabled = NO;
  2872. [alertController addAction:cancelAction];
  2873. [alertController addAction:okAction];
  2874. [self presentViewController:alertController animated:YES completion:nil];
  2875. }];
  2876. }
  2877. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2878. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2879. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  2880. backgroundColor:[UIColor whiteColor]
  2881. height:50.0
  2882. type:AHKActionSheetButtonTypeDefault
  2883. handler:^(AHKActionSheet *as) {
  2884. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2885. }];
  2886. }
  2887. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !isFolderEncrypted) {
  2888. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2889. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  2890. backgroundColor:[UIColor whiteColor]
  2891. height:50.0
  2892. type:AHKActionSheetButtonTypeDefault
  2893. handler:^(AHKActionSheet *as) {
  2894. // Settings new folder Automatatic upload
  2895. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2896. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  2897. // Clear data (old) Auto Upload
  2898. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2899. if (app.activeAccount.length > 0 && app.activePhotos)
  2900. [app.activePhotos reloadDatasourceForced];
  2901. [self readFolder:serverUrl];
  2902. NSLog(@"[LOG] Update Folder Photo");
  2903. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  2904. if ([autoUploadPath length] > 0) {
  2905. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  2906. }
  2907. }];
  2908. }
  2909. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2910. [actionSheet addButtonWithTitle:titoloLock
  2911. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brand]
  2912. backgroundColor:[UIColor whiteColor]
  2913. height:50.0
  2914. type:AHKActionSheetButtonTypeDefault
  2915. handler:^(AHKActionSheet *as) {
  2916. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2917. }];
  2918. }
  2919. if ([CCUtility isEndToEndEnabled:app.activeAccount] && !_metadata.e2eEncrypted && !([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2920. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2921. image:[UIImage imageNamed:@"encrypted_empty"]
  2922. backgroundColor:[UIColor whiteColor]
  2923. height:50.0
  2924. type:AHKActionSheetButtonTypeEncrypted
  2925. handler:^(AHKActionSheet *as) {
  2926. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2927. if ([app.endToEndInterface markEndToEndFolderEncrypted:app.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2928. dispatch_async(dispatch_get_main_queue(), ^{
  2929. [self readFolder:self.serverUrl];
  2930. });
  2931. }
  2932. });
  2933. }];
  2934. }
  2935. if ([CCUtility isEndToEndEnabled:app.activeAccount] && _metadata.e2eEncrypted) {
  2936. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2937. image:[UIImage imageNamed:@"encrypted_empty"]
  2938. backgroundColor:[UIColor whiteColor]
  2939. height:50.0
  2940. type:AHKActionSheetButtonTypeEncrypted
  2941. handler:^(AHKActionSheet *as) {
  2942. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2943. if ([app.endToEndInterface deletemarkEndToEndFolderEncrypted:app.activeUrl fileID:_metadata.fileID serverUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]) {
  2944. dispatch_async(dispatch_get_main_queue(), ^{
  2945. [self readFolder:self.serverUrl];
  2946. });
  2947. }
  2948. });
  2949. }];
  2950. }
  2951. [actionSheet show];
  2952. }
  2953. // ******************************************* FILE *******************************************
  2954. if (!_metadata.directory) {
  2955. UIImage *iconHeader;
  2956. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:self.serverUrl account:app.activeAccount];
  2957. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2958. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  2959. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  2960. else
  2961. iconHeader = [UIImage imageNamed:_metadata.iconName];
  2962. [actionSheet addButtonWithTitle: _metadata.fileNameView
  2963. image: iconHeader
  2964. backgroundColor: [NCBrandColor sharedInstance].tabBar
  2965. height: 50.0
  2966. type: AHKActionSheetButtonTypeDisabled
  2967. handler: nil
  2968. ];
  2969. if (!isFolderEncrypted) {
  2970. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2971. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  2972. backgroundColor:[UIColor whiteColor]
  2973. height: 50.0
  2974. type:AHKActionSheetButtonTypeDefault
  2975. handler:^(AHKActionSheet *as) {
  2976. [self openWindowShare:_metadata];
  2977. }];
  2978. }
  2979. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2980. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  2981. backgroundColor:[UIColor whiteColor]
  2982. height: 50.0
  2983. type:AHKActionSheetButtonTypeDefault
  2984. handler:^(AHKActionSheet *as) {
  2985. [self performSelector:@selector(openIn:) withObject:_metadata];
  2986. }];
  2987. if (!isFolderEncrypted) {
  2988. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2989. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  2990. backgroundColor:[UIColor whiteColor]
  2991. height: 50.0
  2992. type:AHKActionSheetButtonTypeDefault
  2993. handler:^(AHKActionSheet *as) {
  2994. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2995. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2996. textField.text = _metadata.fileNameView;
  2997. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2998. }];
  2999. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3000. NSLog(@"[LOG] Cancel action");
  3001. }];
  3002. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3003. UITextField *fileName = alertController.textFields.firstObject;
  3004. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3005. }];
  3006. okAction.enabled = NO;
  3007. [alertController addAction:cancelAction];
  3008. [alertController addAction:okAction];
  3009. [self presentViewController:alertController animated:YES completion:nil];
  3010. }];
  3011. }
  3012. if (!isFolderEncrypted) {
  3013. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3014. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3015. backgroundColor:[UIColor whiteColor]
  3016. height: 50.0
  3017. type:AHKActionSheetButtonTypeDefault
  3018. handler:^(AHKActionSheet *as) {
  3019. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3020. }];
  3021. }
  3022. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3023. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3024. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3025. backgroundColor:[UIColor whiteColor]
  3026. height: 50.0
  3027. type:AHKActionSheetButtonTypeDefault
  3028. handler:^(AHKActionSheet *as) {
  3029. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3030. }];
  3031. }
  3032. [actionSheet show];
  3033. }
  3034. }
  3035. #pragma --------------------------------------------------------------------------------------------
  3036. #pragma mark - ==== Datasource ====
  3037. #pragma --------------------------------------------------------------------------------------------
  3038. - (void)clearDateReadDataSource:(NSNotification *)notification
  3039. {
  3040. _dateReadDataSource = Nil;
  3041. [self reloadDatasource];
  3042. }
  3043. - (void)reloadDatasource
  3044. {
  3045. [self reloadDatasource:_serverUrl];
  3046. }
  3047. - (void)reloadDatasource:(NSString *)serverUrl
  3048. {
  3049. // test
  3050. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3051. return;
  3052. // Search Mode
  3053. if (_isSearchMode) {
  3054. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil e2eEncryptions:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3055. [self tableViewReloadData];
  3056. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3057. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3058. _noFilesSearchDescription = @"";
  3059. }
  3060. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3061. _noFilesSearchTitle = @"";
  3062. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3063. }
  3064. [self.tableView reloadEmptyDataSet];
  3065. return;
  3066. }
  3067. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3068. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3069. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3070. if (main) {
  3071. [main reloadDatasource];
  3072. } else {
  3073. [self tableViewReloadData];
  3074. [app.activeTransfers reloadDatasource];
  3075. }
  3076. return;
  3077. }
  3078. [app.activeTransfers reloadDatasource];
  3079. // Settaggio variabili per le ottimizzazioni
  3080. _directoryGroupBy = [CCUtility getGroupBySettings];
  3081. _directoryOrder = [CCUtility getOrderSettings];
  3082. // Remove optimization for encrypted directory
  3083. if ([CCUtility isFolderEncrypted:self.serverUrl account:app.activeAccount])
  3084. _dateReadDataSource = nil;
  3085. // Controllo data lettura Data Source
  3086. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3087. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3088. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3089. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3090. _dateReadDataSource = [NSDate date];
  3091. // Data Source
  3092. NSString *sorted = _directoryOrder;
  3093. if ([sorted isEqualToString:@"fileName"])
  3094. sorted = @"fileName";
  3095. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3096. if (directoryID) {
  3097. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3098. NSArray *recordsTableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionsWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3099. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3100. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil e2eEncryptions:recordsTableE2eEncryption groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3101. // get auto upload folder
  3102. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3103. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3104. }
  3105. } else {
  3106. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3107. }
  3108. // is This a Folder Encrypted ?
  3109. _folderEncrypted = [CCUtility isFolderEncrypted:serverUrl account:app.activeAccount];
  3110. [self tableViewReloadData];
  3111. }
  3112. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3113. {
  3114. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3115. if (selectedRows.count > 0) {
  3116. for (NSIndexPath *selectionIndex in selectedRows) {
  3117. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3118. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3119. [metadatas addObject:metadata];
  3120. }
  3121. }
  3122. return metadatas;
  3123. }
  3124. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3125. {
  3126. NSInteger section = indexPath.section + 1;
  3127. NSInteger row = indexPath.row + 1;
  3128. NSInteger totSections = [_sectionDataSource.sections count] ;
  3129. if ((totSections < section) || (section > totSections)) {
  3130. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3131. return nil;
  3132. }
  3133. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3134. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3135. if (fileIDs) {
  3136. NSInteger totRows =[fileIDs count] ;
  3137. if ((totRows < row) || (row > totRows)) {
  3138. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3139. return nil;
  3140. }
  3141. } else {
  3142. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3143. return nil;
  3144. }
  3145. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3146. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3147. return metadata;
  3148. }
  3149. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3150. {
  3151. NSInteger totSections =[_sectionDataSource.sections count] ;
  3152. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3153. return nil;
  3154. }
  3155. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3156. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3157. }
  3158. #pragma --------------------------------------------------------------------------------------------
  3159. #pragma mark - ==== Table ====
  3160. #pragma --------------------------------------------------------------------------------------------
  3161. - (void)tableViewSelect:(BOOL)edit
  3162. {
  3163. // chiudiamo eventuali swipe aperti
  3164. if (edit)
  3165. [self.tableView setEditing:NO animated:NO];
  3166. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3167. [self.tableView setEditing:edit animated:YES];
  3168. _isSelectedMode = edit;
  3169. if (edit)
  3170. [self setUINavigationBarSelected];
  3171. else
  3172. [self setUINavigationBarDefault];
  3173. [_selectedFileIDsMetadatas removeAllObjects];
  3174. [self setTitle];
  3175. }
  3176. - (void)tableViewReloadData
  3177. {
  3178. // store selected cells before relod
  3179. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3180. //store swipeOffset before relod
  3181. [_statusSwipeCell removeAllObjects];
  3182. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3183. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3184. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3185. }
  3186. // reload table view
  3187. [self.tableView reloadData];
  3188. // selected cells stored
  3189. for (NSIndexPath *path in indexPaths)
  3190. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3191. [self setTableViewFooter];
  3192. if (self.tableView.editing)
  3193. [self setTitle];
  3194. }
  3195. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3196. {
  3197. if (tableView.editing == 1) {
  3198. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3199. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3200. return NO;
  3201. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3202. return NO;
  3203. else
  3204. return YES;
  3205. } else {
  3206. [_selectedFileIDsMetadatas removeAllObjects];
  3207. }
  3208. return YES;
  3209. }
  3210. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3211. {
  3212. return 60;
  3213. }
  3214. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3215. {
  3216. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3217. }
  3218. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3219. {
  3220. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3221. }
  3222. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3223. {
  3224. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3225. NSString *sectionTitle = [sections objectAtIndex:section];
  3226. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3227. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3228. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3229. return 20.f;
  3230. }
  3231. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3232. {
  3233. float shift;
  3234. UIVisualEffectView *visualEffectView;
  3235. NSString *titleSection;
  3236. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3237. return nil;
  3238. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3239. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3240. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3241. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3242. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3243. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3244. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3245. else titleSection = NSLocalizedString(titleSection,nil);
  3246. // Format title
  3247. NSString *currentDevice = [CCUtility currentDevice];
  3248. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3249. visualEffectView = [[UIVisualEffectView alloc] init];
  3250. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3251. } else {
  3252. UIVisualEffect *blurEffect;
  3253. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3254. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3255. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3256. }
  3257. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3258. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3259. shift = - 35;
  3260. else
  3261. shift = - 20;
  3262. } else shift = - 10;
  3263. // Title
  3264. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3265. titleLabel.backgroundColor = [UIColor clearColor];
  3266. titleLabel.textColor = [UIColor blackColor];
  3267. titleLabel.font = [UIFont systemFontOfSize:12];
  3268. titleLabel.textAlignment = NSTextAlignmentLeft;
  3269. titleLabel.text = titleSection;
  3270. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3271. [visualEffectView.contentView addSubview:titleLabel];
  3272. // Elements
  3273. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3274. elementLabel.backgroundColor = [UIColor clearColor];
  3275. elementLabel.textColor = [UIColor blackColor];;
  3276. elementLabel.font = [UIFont systemFontOfSize:12];
  3277. elementLabel.textAlignment = NSTextAlignmentRight;
  3278. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3279. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3280. NSUInteger rowsCount = [metadatas count];
  3281. if (rowsCount == 0) return nil;
  3282. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3283. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3284. [visualEffectView.contentView addSubview:elementLabel];
  3285. return visualEffectView;
  3286. }
  3287. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3288. {
  3289. return [_sectionDataSource.sections indexOfObject:title];
  3290. }
  3291. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3292. {
  3293. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3294. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3295. else
  3296. return nil;
  3297. }
  3298. /*
  3299. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3300. {
  3301. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3302. }
  3303. }
  3304. */
  3305. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3306. {
  3307. NSString *typeCell;
  3308. NSString *dataFile;
  3309. NSString *lunghezzaFile;
  3310. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3311. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3312. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3313. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3314. if (!serverUrl)
  3315. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3316. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3317. else typeCell = @"CellMainTransfer";
  3318. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3319. // variable base
  3320. cell.delegate = self;
  3321. cell.indexPath = indexPath;
  3322. // separator
  3323. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3324. // change color selection
  3325. UIView *selectionColor = [[UIView alloc] init];
  3326. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3327. cell.selectedBackgroundView = selectionColor;
  3328. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3329. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3330. // ----------------------------------------------------------------------------------------------------------
  3331. // DEFAULT
  3332. // ----------------------------------------------------------------------------------------------------------
  3333. cell.file.image = nil;
  3334. cell.status.image = nil;
  3335. cell.favorite.image = nil;
  3336. cell.shared.image = nil;
  3337. cell.local.image = nil;
  3338. cell.labelTitle.enabled = YES;
  3339. cell.labelTitle.text = @"";
  3340. cell.labelInfoFile.enabled = YES;
  3341. cell.labelInfoFile.text = @"";
  3342. cell.progressView.progress = 0.0;
  3343. cell.progressView.hidden = YES;
  3344. cell.cancelTaskButton.hidden = YES;
  3345. cell.reloadTaskButton.hidden = YES;
  3346. cell.stopTaskButton.hidden = YES;
  3347. cell.labelTitle.textColor = [UIColor blackColor];
  3348. // ----------------------------------------------------------------------------------------------------------
  3349. // File Name & Folder
  3350. // ----------------------------------------------------------------------------------------------------------
  3351. // nome del file
  3352. cell.labelTitle.text = metadata.fileNameView;
  3353. // è una directory
  3354. if (metadata.directory) {
  3355. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3356. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3357. lunghezzaFile = @" ";
  3358. // ----------------------------------------------------------------------------------------------------------
  3359. // Favorite Folder
  3360. // ----------------------------------------------------------------------------------------------------------
  3361. if (metadata.favorite) {
  3362. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3363. }
  3364. } else {
  3365. // File
  3366. dataFile = [CCUtility dateDiff:metadata.date];
  3367. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3368. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3369. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3370. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3371. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3372. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3373. cell.local.image = [UIImage imageNamed:@"local"];
  3374. else
  3375. cell.local.image = nil;
  3376. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3377. cell.accessoryType = UITableViewCellAccessoryNone;
  3378. }
  3379. // ----------------------------------------------------------------------------------------------------------
  3380. // File Image View
  3381. // ----------------------------------------------------------------------------------------------------------
  3382. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3383. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3384. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3385. } else {
  3386. if (metadata.directory) {
  3387. if (metadata.e2eEncrypted)
  3388. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brand];
  3389. else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory])
  3390. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand];
  3391. else
  3392. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brand];
  3393. } else {
  3394. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3395. }
  3396. if (metadata.thumbnailExists)
  3397. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3398. }
  3399. // ----------------------------------------------------------------------------------------------------------
  3400. // Image Status Lock Passcode
  3401. // ----------------------------------------------------------------------------------------------------------
  3402. // Directory con passcode lock attivato
  3403. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3404. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3405. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3406. cell.status.image = [UIImage imageNamed:@"passcode"];
  3407. // ----------------------------------------------------------------------------------------------------------
  3408. // Image Status Encrypted
  3409. // ----------------------------------------------------------------------------------------------------------
  3410. if (_folderEncrypted && !metadata.directory) {
  3411. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", app.activeAccount, metadata.fileName]];
  3412. if (tableE2eEncryption)
  3413. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3414. }
  3415. // ----------------------------------------------------------------------------------------------------------
  3416. // Favorite
  3417. // ----------------------------------------------------------------------------------------------------------
  3418. if (metadata.favorite) {
  3419. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3420. }
  3421. // ----------------------------------------------------------------------------------------------------------
  3422. // Share
  3423. // ----------------------------------------------------------------------------------------------------------
  3424. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3425. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3426. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3427. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3428. // Aggiungiamo il Tap per le shared
  3429. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3430. // Shared with you
  3431. if (isShare) {
  3432. if (metadata.directory) {
  3433. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3434. cell.accessoryType = UITableViewCellAccessoryNone;
  3435. }
  3436. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3437. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3438. [tap setNumberOfTapsRequired:1];
  3439. cell.shared.userInteractionEnabled = YES;
  3440. [cell.shared addGestureRecognizer:tap];
  3441. }
  3442. // Mounted with you
  3443. if (isMounted) {
  3444. if (metadata.directory) {
  3445. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3446. cell.accessoryType = UITableViewCellAccessoryNone;
  3447. }
  3448. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3449. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3450. [tap setNumberOfTapsRequired:1];
  3451. cell.shared.userInteractionEnabled = YES;
  3452. [cell.shared addGestureRecognizer:tap];
  3453. }
  3454. // You share
  3455. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3456. if (metadata.directory) {
  3457. if ([shareLink length] > 0)
  3458. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3459. if ([shareUserAndGroup length] > 0)
  3460. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3461. cell.shared.userInteractionEnabled = NO;
  3462. } else {
  3463. if ([shareLink length] > 0)
  3464. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3465. if ([shareUserAndGroup length] > 0)
  3466. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3467. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3468. [tap setNumberOfTapsRequired:1];
  3469. cell.shared.userInteractionEnabled = YES;
  3470. [cell.shared addGestureRecognizer:tap];
  3471. }
  3472. }
  3473. } else {
  3474. cell.shared.userInteractionEnabled = NO;
  3475. }
  3476. // ----------------------------------------------------------------------------------------------------------
  3477. // downloadFile
  3478. // ----------------------------------------------------------------------------------------------------------
  3479. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3480. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3481. // sessionTaskIdentifier : RELOAD + STOP
  3482. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3483. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3484. cell.cancelTaskButton.hidden = NO;
  3485. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3486. cell.reloadTaskButton.hidden = NO;
  3487. }
  3488. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3489. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3490. if (progress > 0) {
  3491. cell.progressView.progressTintColor = [UIColor blackColor];
  3492. cell.progressView.progress = progress;
  3493. cell.progressView.hidden = NO;
  3494. }
  3495. // ----------------------------------------------------------------------------------------------------------
  3496. // downloadFile Error
  3497. // ----------------------------------------------------------------------------------------------------------
  3498. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3499. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3500. if ([metadata.sessionError length] == 0) {
  3501. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3502. } else {
  3503. cell.labelInfoFile.text = metadata.sessionError;
  3504. }
  3505. }
  3506. }
  3507. // ----------------------------------------------------------------------------------------------------------
  3508. // uploadFile
  3509. // ----------------------------------------------------------------------------------------------------------
  3510. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3511. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3512. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3513. cell.cancelTaskButton.hidden = NO;
  3514. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3515. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3516. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3517. cell.reloadTaskButton.hidden = NO;
  3518. cell.stopTaskButton.hidden = YES;
  3519. } else {
  3520. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3521. cell.stopTaskButton.hidden = NO;
  3522. cell.reloadTaskButton.hidden = YES;
  3523. }
  3524. // se non c'è una preview in bianconero metti l'immagine di default
  3525. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3526. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3527. cell.labelTitle.enabled = NO;
  3528. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3529. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3530. if (progress > 0) {
  3531. cell.progressView.progressTintColor = [UIColor blackColor];
  3532. cell.progressView.progress = progress;
  3533. cell.progressView.hidden = NO;
  3534. }
  3535. // ----------------------------------------------------------------------------------------------------------
  3536. // uploadFileError
  3537. // ----------------------------------------------------------------------------------------------------------
  3538. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3539. cell.labelTitle.enabled = NO;
  3540. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3541. if ([metadata.sessionError length] == 0) {
  3542. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3543. } else {
  3544. cell.labelInfoFile.text = metadata.sessionError;
  3545. }
  3546. }
  3547. }
  3548. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3549. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3550. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3551. // ======== MGSwipe ========
  3552. if (metadata.favorite)
  3553. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3554. else
  3555. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3556. cell.leftExpansion.buttonIndex = 0;
  3557. cell.leftExpansion.fillOnTrigger = NO;
  3558. //centerIconOverText
  3559. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3560. [favoriteButton centerIconOverText];
  3561. //Right
  3562. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3563. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3564. //centerIconOverText
  3565. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3566. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3567. [deleteButton centerIconOverText];
  3568. [moreButton centerIconOverText];
  3569. //restore swipeOffset after relod
  3570. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3571. if (swipeOffset < 0) {
  3572. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3573. [_statusSwipeCell removeObjectForKey:indexPath];
  3574. } else if (swipeOffset > 0) {
  3575. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3576. [_statusSwipeCell removeObjectForKey:indexPath];
  3577. }
  3578. return cell;
  3579. }
  3580. - (void)setTableViewFooter
  3581. {
  3582. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3583. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3584. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3585. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3586. UIFont *appFont = [UIFont systemFontOfSize:12];
  3587. footerLabel.font = appFont;
  3588. footerLabel.textColor = [UIColor grayColor];
  3589. footerLabel.backgroundColor = [UIColor clearColor];
  3590. footerLabel.textAlignment = NSTextAlignmentCenter;
  3591. NSString *folders;
  3592. NSString *files;
  3593. NSString *footerText;
  3594. if (_sectionDataSource.directories > 1) {
  3595. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3596. } else if (_sectionDataSource.directories == 1){
  3597. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3598. } else {
  3599. folders = @"";
  3600. }
  3601. if (_sectionDataSource.files > 1) {
  3602. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3603. } else if (_sectionDataSource.files == 1){
  3604. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3605. } else {
  3606. files = @"";
  3607. }
  3608. if ([folders isEqualToString:@""]) {
  3609. footerText = files;
  3610. } else if ([files isEqualToString:@""]) {
  3611. footerText = folders;
  3612. } else {
  3613. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3614. }
  3615. footerLabel.text = footerText;
  3616. [footerView addSubview:footerLabel];
  3617. [self.tableView setTableFooterView:footerView];
  3618. }
  3619. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3620. {
  3621. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3622. // settiamo il record file.
  3623. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3624. if (!_metadata)
  3625. return;
  3626. // se non può essere selezionata deseleziona
  3627. if ([cell isEditing] == NO)
  3628. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3629. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3630. if (self.tableView.editing) {
  3631. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3632. [self setTitle];
  3633. return;
  3634. }
  3635. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3636. if (!serverUrl) return;
  3637. // se è in corso una sessione
  3638. if ([_metadata.session length] > 0) return;
  3639. // file
  3640. if (_metadata.directory == NO) {
  3641. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3642. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3643. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3644. } else {
  3645. if ([CCUtility isFolderEncrypted:self.serverUrl account:app.activeAccount] && ![CCUtility isEndToEndEnabled:app.activeAccount]) {
  3646. [app messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3647. } else {
  3648. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3649. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3650. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3651. }
  3652. }
  3653. }
  3654. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3655. }
  3656. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3657. {
  3658. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3659. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3660. [self setTitle];
  3661. }
  3662. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3663. {
  3664. if (!indexPath)
  3665. return NO;
  3666. NSInteger section = indexPath.section;
  3667. NSInteger row = indexPath.row;
  3668. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3669. if (section > lastSectionIndex || lastSectionIndex < 0)
  3670. return NO;
  3671. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3672. if (rowCount < 0)
  3673. return NO;
  3674. return row <= rowCount;
  3675. }
  3676. #pragma --------------------------------------------------------------------------------------------
  3677. #pragma mark ===== Navigation ====
  3678. #pragma --------------------------------------------------------------------------------------------
  3679. - (BOOL)shouldPerformSegue
  3680. {
  3681. // if background return
  3682. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3683. if (self.view.window == NO)
  3684. return NO;
  3685. // Collapsed ma siamo già in detail esci
  3686. if (self.splitViewController.isCollapsed)
  3687. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3688. return YES;
  3689. }
  3690. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3691. {
  3692. id viewController = segue.destinationViewController;
  3693. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3694. tableMetadata *metadata;
  3695. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3696. UINavigationController *nav = viewController;
  3697. _detailViewController = (CCDetail *)nav.topViewController;
  3698. } else {
  3699. _detailViewController = segue.destinationViewController;
  3700. }
  3701. if ([sender isKindOfClass:[tableMetadata class]]) {
  3702. metadata = sender;
  3703. [allRecordsDataSourceImagesVideos addObject:sender];
  3704. } else {
  3705. metadata = _metadata;
  3706. for (NSString *fileID in _sectionDataSource.allEtag) {
  3707. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3708. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3709. [allRecordsDataSourceImagesVideos addObject:metadata];
  3710. }
  3711. }
  3712. _detailViewController.metadataDetail = metadata;
  3713. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3714. _detailViewController.dateFilterQuery = nil;
  3715. [_detailViewController setTitle:metadata.fileName];
  3716. }
  3717. // can i go to next viewcontroller
  3718. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3719. {
  3720. NSString *nomeDir;
  3721. if(self.tableView.editing == NO) {
  3722. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3723. if (!serverUrl) return;
  3724. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3725. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3726. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3727. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3728. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3729. viewController.delegate = self;
  3730. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3731. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3732. viewController.inputViewTitlePassword = YES;
  3733. if ([CCUtility getSimplyBlockCode]) {
  3734. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3735. viewController.passcodeInputView.maximumLength = 6;
  3736. } else {
  3737. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3738. viewController.passcodeInputView.maximumLength = 64;
  3739. }
  3740. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3741. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3742. viewController.touchIDManager = touchIDManager;
  3743. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3744. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3745. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3746. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3747. [self presentViewController:navController animated:YES completion:nil];
  3748. return;
  3749. }
  3750. nomeDir = _metadata.fileName;
  3751. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3752. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3753. if (!viewController) {
  3754. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3755. viewController.serverUrl = serverUrlPush;
  3756. viewController.titleMain = _metadata.fileName;
  3757. viewController.textBackButton = _titleMain;
  3758. // save self
  3759. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3760. [self.navigationController pushViewController:viewController animated:YES];
  3761. } else {
  3762. if (viewController.isViewLoaded) {
  3763. // Fix : Application tried to present modally an active controller
  3764. if ([self.navigationController isBeingPresented]) {
  3765. // being presented
  3766. } else if ([self.navigationController isMovingToParentViewController]) {
  3767. // being pushed
  3768. } else {
  3769. [self.navigationController pushViewController:viewController animated:YES];
  3770. }
  3771. }
  3772. }
  3773. }
  3774. }
  3775. @end