CCMain.m 228 KB

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